How to get Byte[] from an image object?

This are the codes that i have tried, it did an resized.jpg but the file doesnt consist of the image. My program will stream the .jpg file using fileconnection then i resize the image and created the new image using image.createRGBImage(). Lastly, i need to save the resized image as a jpeg file but i failed to do so..
byte[] jpegData = ImageByteConverter.getByteArray(image);
OutputStream out = fconn.openOutputStream();
out.write(jpegData,0,jpegData.length);
* This method converts a int-array, containing all RGB values for the image, to
* a byte-array containing all RGB values.
public static byte[] getByteArray(Image image){
// Allocate new memory for the int-array and fill the array in the getRGB method.
int[]raw = new int[image.getWidth() * image.getHeight()];
image.getRGB(raw, 0, image.getWidth(), 0, 0, image.getWidth(), image.getHeight());
byte[]rawByte = new byte[image.getWidth() * image.getHeight() * 4];// ARGB
int a, r, g, b;
int n = 0;
// loop through the int-array and get the 4 bytes of each value to the byte-array.
// since java isn't supporting unsigned bytes we need to store the ARGB values from -128 to 127
// where -128 = 128, -127 = 129 and -1 = 255
for(int i=0; i<raw.length; i++){
// Right-shift the values to fit in a byte.
int ARGB = raw;
a = (ARGB & 0xFF000000) >> 24;
r = (ARGB & 0xFF0000) >> 16;
g = (ARGB & 0xFF00) >> 8;
b = (ARGB & 0xFF);
rawByte[n] = (byte)b;
rawByte[n+1] = (byte)g;
rawByte[n+2] = (byte)r;
rawByte[n+3] = (byte)a;
n+=4;
raw=null;
return rawByte;
Thanks in advance.

you can do follwoing but not sure whether thats what you want.
Also not sure whether its the best way.
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(image, "PNG",baos);
InputStream in = new ByteArrayInputStream(baos.toByteArray());

Similar Messages

  • In XI mapping, how to get number from a number_range object in SAP R/3

    HI All,
    I have a scenario where I need to read a Number_range object  in SAP R/3 or ABAP XI and retreive the current number.
    I need to use this number during the message mapping.
    (I read about JCO and RFC, but am a little confused about how-to and what is the correct approach)
    Just to let you know, I do not want to pass this number in the original IDOC coming from IDOC, so I need this lookup.
    Scenario:
    In MM, make a call to SAP.
    Get the latest number from SNRO( number-range object)
    Use this number in mapping.
    Any help pointers, greatly appreciated.
    Many thanks
    Shirin

    Shrin,
    Please find the parameters you need to specify while creating UDF
    Imports:javax.xml.transform.stream.StreamResult;com.sap.aii.mapping.lookup.;javax.xml.transform.dom.DOMSource;javax.xml.parsers.DocumentBuilder;java.io.;javax.xml.parsers.;org.w3c.dom.;org.xml.sax.;javax.xml.transform.;
    The Template for RFC Lookup
    String content = "";
    MappingTrace importanttrace;
    importanttrace = container.getTrace() ;
    //Filling the string with our RFC-XML (With Values)
    String m = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><ns0:<Function Module name>xmlns:ns0=\"urn:sap-com:document:sap:rfc:functions\"></ns0:ZFI_GET_RUNID> ";
    RfcAccessor accessor = null;
    ByteArrayOutputStream out = null;
    try
    //1. Determine a channel (Business System, Communication channel)
    Channel channel = LookupService.getChannel("<Business System Name>","Communication channel name");
    //2. Get a RFC accesor for a channel.
    accessor = LookupService.getRfcAccessor(channel);
    //3. Create a xml input stream representing the FM request message.
    InputStream inputstream = new ByteArrayInputStream(m.getBytes());
    //4. Create xml Payload
    XmlPayload payload  =  LookupService.getXmlPayload(inputstream);
    //5. Execute Lookup
    Payload result = accessor.call(payload);
    InputStream in = result.getContent();
    //This are the extra step which i dont know what it mean
    //out = new ByteArrayOutputStream(1024);
    //byte[] buffer = new byte[1024];
    //for (int read = in.read(buffer); read > 0; read = in.read(buffer))
    //out.write(buffer,0,read);
    //content = out.toString();
    try {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document document = builder.parse(in);
    NodeList list = document.getElementsByTagName( "REsult" );
    Node node = list.item(0);
    if (node  != null)
         node = node.getFirstChild();
         if (node  != null)
              content = node.getNodeValue();
    } catch (Exception e) {
    importanttrace.addWarning("Error while closing accesor" + e.getMessage());
    catch (LookupException e)
    importanttrace.addWarning("Error While lookup" + e.getMessage());
    //This exception is not to be catch at this step as there is no try step before this
    //catch (IOException e)
    //importanttrace.addWarning("Error" + e.getMessage());
    finally
    if(out!=null)
      try{
           out.close();
    } catch (IOException e) {
    importanttrace.addWarning("Error while closing system" + e.getMessage());
    //7. close the accessor in order to free resources
    if (accessor!=null) {
    try{
          accessor.close();
    } catch (Exception e) {
    importanttrace.addWarning("Error while closing accesor" + e.getMessage());
    return content;
    Have mentioned in genric  where u need to specify the communication channel name, business service etc.,
    Moreover there is a field result, which is the output returned from the FM

  • Get bytes from image

    Hi,
    Can someone please tell me how to get the bytes from an Image object in an applet. I need to send the data to php or asp script to save to image file on server. Preferably in jpeg format if thats possible. Thanks.

    what i need is to save an Image object to the server. I have written all the applet functionality in editing the image in various ways i just need to know how to get all the data and transform to jpeg data that can be sent from applet to a php script that simply writes the data it recieves to the disk. so far all ive been able to do is get short things like [B@4e2f0a to be written to the file on server. can someone please direct me as to waht i need to do and show me working code example or something. thanks alot.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • How to get the values of the objects inside an object??

    Hi,
    I am trying to write code to display name and memory usage of all session attributes, in a recursive way.
    I suppose reflection is needed here, but I can’t figure out how to get the values of the objects inside an object...
    private void handleIt(String attributeName, Object attributeValue) {
         boolean isPrimitiveOrNull = ((null == attributeValue) ||
              (attributeValue.getClass().isPrimitive()));                                         
         if (isPrimitiveOrNull) {
              sb.append("{" + attributeName + ":" + sizeOf(attributeValue) + "}");
         } else {
              sb.append("{" + attributeName + ":" + sizeOf(attributeValue) + "{");               
              Field[] fields = attributeValue.getClass().getDeclaredFields();
              int lim = fields.length;
              String name;
              Object value = null;
              for (int i = 0; i < lim; i++) {
                   name = fields.getName();
                   //LOOK AT THIS LINE: !!!!!!!!!!!!!!!!!!!!!!!!!!!
                   value = fields[i].get(obj); //I don´t know what 'obj' should be??
                   handleIt(name, value);
              sb.append("}");               
    Any suggestions will be greatly appreciated...

    I realized that massive int objects called MAX_VALUE, MIN_VALUE and SIZE where causing the StackOverflow, so I removed them from the analysis.
    This is the resultant code. But I think it isn’t accurate in calculating the real size of objects being got using reflexion.
    Do you or somebody have any more suggestions?
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    import java.io.ObjectOutputStream;
    import java.lang.reflect.Field;
    import java.util.Enumeration;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    public class SessionMeasurer extends HttpServlet {
         private static final long serialVersionUID = 1470488362727841992L;
         private StringBuilder sb = new StringBuilder();
         public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
              performTask(request, response);
         public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
              performTask(request, response);
         public void performTask(HttpServletRequest request, HttpServletResponse response) {
              HttpSession     session = request.getSession(false);     
              String attributeName = "";
              Object attributeValue = null;
              for (Enumeration<?> attributeNames = session.getAttributeNames(); attributeNames.hasMoreElements();) {
                   attributeName = (String)attributeNames.nextElement();
                   attributeValue = session.getAttribute(attributeName);
                   handleIt(attributeName, attributeValue);               
              System.out.println(sb.toString());
         private void handleIt(String attributeName, Object attributeValue) {           
              if (attributeValue != null) {          
                   boolean isPrimitive = attributeValue.getClass().isPrimitive();
                   if (isPrimitive) {
                        sb.append("{" + attributeName + ":" + sizeOf(attributeValue) + "}");
                   } else {
                        sb.append("{" + attributeName + ":" + sizeOf(attributeValue) + "{");               
                        Field[] fields = attributeValue.getClass().getDeclaredFields();
                        String name;
                        Object value = null;
                        int lim = fields.length;
                        for (int i = 0; i < lim; i++) {
                             name = fields.getName();                                                                                                         
                             if (!name.endsWith("_VALUE") && !name.equals("SIZE") && !name.equals("serialVersionUID")) {
                                  try {
                                       value = fields[i].get(attributeValue);
                                  } catch(Exception e) {
                                       //PENDIENTE: Tratamiento excepción
                                  handleIt(name, value);
                        sb.append("}");               
         private int sizeOf(Object obj) {
              //Valid only for Serializables
              ByteArrayOutputStream baos = new ByteArrayOutputStream();
              ObjectOutputStream oos = null;     
              byte[] bytes = null;               
              try {          
                   oos = new ObjectOutputStream(baos);
                   oos.writeObject(obj);
                   bytes = baos.toByteArray();
              } catch(Exception e) {               
                   //PENDIENTE: Tratamiento excepción
              } finally {
                   if (oos != null) {
                        try {
                             oos.close();
                        } catch(Exception e) {
                             //PENDIENTE: Tratamiento excepción                         
                   if (baos != null) {
                        try {
                             baos.close();
                        } catch(Exception e) {
                             //PENDIENTE: Tratamiento excepción                         
              int size = -1;
              if (bytes != null) {
                   size = bytes.length;
              return size;          

  • How to get value from list item

    Hi all,
    How to get value from list item?
    I have a problem with the List Item object
    in the Oracle forms.
    How can I retrieve the selected item from
    a list ?
    I didn't find any function like 'list.GET_
    SELECTED_ITEM()'...
    thanks
    Bala

    Hello,
    You get the value as for any other Forms item:
    :value := :block.list_tem ;Francois

  • Best way to get bytes from a ByteBuffer

    Hi,
    I see three possible ways to get the bytes from a ByteBuffer in a new byte array. (if I get the backed array, a change in that array will change the ByteBuffer, that's why I insist on new array).
    1. System.arraycopy on the backed array
    2. clone() on the backed array
    3. use ByteBuffer's get() method
    Which one is the best in terms of performance ?
    Thank you for any tips.

    This Java tip demonstrates a method of getting bytes from a ByteBuffer. A ByteBuffer has a capacity that determines how many bytes it contains. This capacity can never change. The bytes in a ByteBuffer can also be retrieved using the relative version of get [cheapest wow gold|http://www.wowgoldstudio.com/] (), which uses the position and limit properties of the buffer. In particular, this version of get() retrieves the byte at the position and advances the position by one. get() cannot retrieve bytes past the limit (even though the limit might be less than the capacity). The position is always <= limit and limit is always <= capacity.
    [cheap wow gold|http://www.wow-goldstore.com/]
    // Create an empty ByteBuffer with a 10 byte capacity
    ByteBuffer bbuf = ByteBuffer.allocate(10);
    // Retrieve the capacity of the ByteBuffer
    int capacity = bbuf.capacity(); // 10
    // The position is not affected by the absolute get() method.
    byte b = bbuf.get(5); // position=0
    // Set the position
    bbuf.position(5);
    // Use the relative get()
    b = bbuf.get();
    // Get the new position
    int pos = bbuf.position(); // 6
    // Get remaining byte count
    int rem = bbuf.remaining(); // 4
    // Set the limit
    bbuf.limit(7); // remaining=1
    // This convenience method sets the position to 0
    bbuf.rewind(); // remaining=7
    Edited by: veewei on May 4, 2010 7:31 PM

  • How to add byte[] array based Image to the SQL Server without using parameter

    how to add byte[] array based Image to the SQL Server without using parameter.I have a column in table with the type image in sql and i want to add image array to the sql image column like below:
    I want to add image (RESIM) to the procedur like shown above but sql accepts byte[] RESIMI like System.Drowing. I whant that  sql accepts byte [] array like sql  image type
    not using cmd.ParametersAdd() method
    here is Isle() method content

    SQL Server binary constants use a hexadecimal format:
    https://msdn.microsoft.com/en-us/library/ms179899.aspx
    You'll have to build that string from a byte array yourself:
    byte[] bytes = ...
    StringBuilder builder = new StringBuilder("0x", 2 + bytes.Length * 2);
    foreach (var b in bytes)
    builder.Append(b.ToString("X2"));
    string binhex = builder.ToString();
    That said, what you're trying to do - not using parameters - is the wrong thing to do. Not only it is insecure due to the risk of SQL injection but in the case of binary data is also inefficient since these hex strings are larger than the original byte[]
    data.

  • How to get videos from my camera on ipad 2 to my iMac

    how to get videos from my camera on ipad 2 to my iMac

    Photos/videos in the Camera Roll can be imported by your computer as with any other digital camera.
    If you use iPhoto for this with any other digital camera, you can use iPhoto for this. Or you can use the Image Capture application for the import if you don't use iPhoto.

  • How to get string from jtextpane along with its attributes

    sir,
    How to get string from jtextpane along with its attributes
    i,e font,size,style,color etc.
    please help me out.
    my mail id is [email protected]

    JTextPane extends JTextComponent
    JTextComponent.getDocument()
    a Document is a set of Element, see Document.getRootElements(). Each Element has attributes, stored within an AttributSet object see Element.getAttributes()
    a Document can also be rendered as a String, see Document.getText( offest, length ), use it with 0 and Document.getLength() as parameters.

  • The float in windows option is grey and not accessable ? How can I copy from one image to another ? Elements 11

    The float all in windows option is grey and not accessible ? How can I copy from one image to another ? Elements 11

    You really are not getting this.
    "I guess I am still completely shocked that as a parent we can't download something for everyone to use."
    Why do you continue to think this although we keep telling you that this is not the case.
    You do NOT have to purchase anything twice.  You can share the music with as many ipods as you like in your household.
    The ipods are designed to sync with your computer regularly.  You should have been syncing these other ipods with your computer all along, thus transferring the purchases to your computer where that music can be synced to as many ipods as you like.
    Take on of the ipods with the music in it.  Open itunes on your computer.  Plug in the ipod.  Do not sync.  Click File>Transfer Purchases  This will transfer the purchases from the ipod to the computer.  Make sure that you have authorized your account on the computer:  here are directions for that. http://support.apple.com/kb/HT1420
    Unplug the ipod.
    Plug in the other ipod with purchased music.  Do not sync.  Click File>Transfer Purchases  This will transfer purchases from the ipod to the computer.
    You can now plug in any of the ipods, select what you want to sync and sync.
    Have a look at the manual for the ipod.  http://manuals.info.apple.com/en_US/iPod_touch_iOS4_User_Guide.pdf

  • How to get event when any library object added to indesign doc?

    I want to do some operation when any library object is added to doc. So please tell me how to get event when any library object is added to the doc. better provide some code snippet.

    Daves61,
    I need to clarify what kind of event you're interested in.
    1. When you click once on page/spead widget in the Pages panel and only widget becomes selected. The layout window remains unchanged. OR
    2. When you doubleclick on page/spread widget the selected master spread appears in the layout window.
    In the first case you work with Pages panel.
    Have a look to file PageTransitionsPanelObserver.cpp from SDK. 
    PageTransitionsPanelObserver::LazyUpdate()
    In the second case you work with Layout window.

  • How to convert bytes[] into multipage File object

    Hi,
    How to convert bytes[] into multipage File object??
    I used the java.io.SequenceInputStream to concatenate two input streams (basically .pdf files) into a single input stream. I need to create a single multipage pdf file using this input stream.
    Thanks for you help in advance..

    Only text format allows you to concatenate two files together to get a longer files.
    Most formats have a header and a footer and so you cannot simply add one to the other.
    You need to use a PDF API which will allow you to build the new document (if one exists)

  • How to get photos from mac to iPhone 6? when i try it just comes up iCloud instead of my photos

    how to get photos from mac to iPhone 6? when i try it just comes up iCloud instead of my photos

    Make sure Settings > iCloud > Photos > iCloud Photo Library (Beta) = "Off"
    Then sync your iPhone using iTunes and make sure your sync settings for photos are set correctly in iTunes.

  • I got a new computer and don't know how to get music from ipod touch to itunes library

    I recently got a new computer and don't know how to get music from my ipod touch to show on my itunes library. 

    You need to transfer the iTunes folder from the old computer to the new one.
    iTunes: How to move your music to a new computer (Mac or Windows):
      http://support.apple.com/kb/HT4527

  • I have a new MacAir and don't know how to get info from my USB stick and my SD photo card.  Can anyone help me please?

    I have a new MacBook Air and don't know how to get info from my USB stick and get info from my SD card.  Can anyone help, please?

    Plug the stick and/or card into the appropriate slots on the side of your Air. Do you see icons for the devices appear on the desktop? Click into them to see what files are there.
    Matt

Maybe you are looking for