How to get a string or byte array representation of an Image/BufferedImage?

I have a java.awt.Image object that I want to transfer to a server application (.NET) through a http post request.
To do that I would like to encode the Image to jpeg format and convert it to a string or byte array to be able to send it in a way that the receiver application (.NET) could handle. So, I've tried to do like this.
private void send(Image image) {
    int width = image.getWidth(null);
    int height = image.getHeight(null);
    try {
        BufferedImage buffImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        ImageIcon imageIcon = new ImageIcon(image);
        ImageObserver observer = imageIcon.getImageObserver();
        buffImage.getGraphics().setColor(new Color(255, 255, 255));
        buffImage.getGraphics().fillRect(0, 0, width, height);
        buffImage.getGraphics().drawImage(imageIcon.getImage(), 0, 0, observer);
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        JPEGImageEncoder jpeg = JPEGCodec.createJPEGEncoder(stream);
        jpeg.encode(buffImage);
        URL url = new URL(/* my url... */);
        URLConnection connection = url.openConnection();
        String boundary = "--------" + Long.toHexString(System.currentTimeMillis());
        connection.setRequestProperty("method", "POST");
        connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
        String output = "--" + boundary + "\r\n"
                      + "Content-Disposition: form-data; name=\"myImage\"; filename=\"myFilename.jpg\"\r\n"
                      + "Content-Type: image/jpeg\r\n"
                      + "Content-Transfer-Encoding: base64\r\n\r\n"
                      + new String(stream.toByteArray())
                      + "\r\n--" + boundary + "--\r\n";
        connection.setDoOutput(true);
        connection.getOutputStream().write(output.getBytes());
        connection.connect();
    } catch {
}This code works, but the image I get when I save it from the receiver application is distorted. The width and height is correct, but the content and colors are really weird. I tried to set different image types (first line inside the try-block), and this gave me different distorsions, but no image type gave me the correct image.
Maybe I should say that I can display the original Image object on screen correctly.
I also realized that the Image object is an instance of BufferedImage, so I thought I could skip the first six lines inside the try-block, but that doesn't help. This way I don't have to set the image type in the constructor, but the result still is color distorted.
Any ideas on how to get from an Image/BufferedImage to a string or byte array representation of the image in jpeg format?

Here you go:
  private static void send(BufferedImage image) throws Exception
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    ImageIO.write(image, "jpeg", byteArrayOutputStream);
    byte[] imageByteArray = byteArrayOutputStream.toByteArray();
    URL url = new URL("http://<host>:<port>");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setDoOutput(true);
    connection.setRequestMethod("POST");
    OutputStream outputStream = connection.getOutputStream();
    outputStream.write(imageByteArray, 0, imageByteArray.length);
    outputStream.close();
    connection.connect();
    // alternative to connect is to get & close the input stream
    // connection.getInputStream().close();
  }

Similar Messages

  • How to get the string's byte length?

    I have some string,I want to get the string's byte length,how
    can do it?
    for example:
    <cfoutput>#len('hihi,这是测试')#</cfoutput>
    output is 9
    I want to get the byte length is 14, how can i get it?
    Thanks.

    >> Fair cop. I didn't realise that asc() returned the
    codepoint rather than the
    > actual character code.
    >
    > and what would be the difference?
    Oh, sorry, whatever the term is (I'm crap with jargon). The
    value returned
    by asc() for those chars was only two bytes (ie: four hex
    digits). I
    didn't realise there was more to it than that, and that
    2-byte value maps
    to some other THREE byte value. I need to do some reading...
    > that's what both cf & java counted as the length.
    CHARACTER length, sure. No-one's disputing that. On the other
    hand,
    no-one's asking about it, either.
    > by adding a BOM you've already effected the encoding,
    which may or may not
    > match the original. so you still don't know how many
    bytes were in the original
    > string.
    [groan]
    Yes, that's a reasonable strawman there. I was only putting
    it in a file
    so I could save it and check the number of bytes occupied by
    the data.
    Clearly... CLEARLY... the OP is not asking for a character
    length of that
    string. They've said as much.
    I copy and pasted the string from their post, and used it as
    a
    demonstration of how "nine" is not the right answer for the
    BYTE LENGTH of
    that string. Whether or not the original string was UTF-8,
    UTF-16 or
    special-marmoset-encoding, it almost certainly was NOT in a
    fictitious kind
    encoding in which each of those particular characters only
    occupied one
    byte each, which would mean that "nine" is the correct answer
    to the
    question.
    When I copied those characters from either the web browser
    for from my
    text-based news agent, notepad identified them (and rendered
    them
    correctly) as UTF-8, so I'm fairly confident they ARE UTF-8.
    Of course
    this could be down to some intermediary encoding (pasting
    them in to the
    original posting, for example, via some encoding-transforming
    mechanism),
    but Occam's Razor suggests the original question was from a
    UTF-8 POV.
    But maybe we should quit speculating and ask the OP. Unless
    they've
    buggered off in despair of how drawn out all this is getting.
    For which I
    would not blame them.
    Adam

  • How to get the number of bytes at TCP port

    Hi all,
    How to get the number of bytes to read at the TCp port...as someone had suggested in some forum we do read the number of bytes first and then pass this...
    but we get a problem when we have FF data in this...because then it sends 2 FF data...and cause of this we skip the last data...is there any solution for the same?

    Hi
    In LabVIEW you don't have the same property as in serail port.
    You havn't "Byte at TCPIP port".
    if you developp a protocol, one soltion, is to send the size to read.
    Ingénieur d'Application / Développeur LabVIEW Certifié (CLD)
    Application Engineer / LabVIEW Certified Developer (CLD)

  • How to get more than 256 bytes data

    hello.
    I use Schlumberger 32K Card�iJava Card 2.1�j.
    Please tell me how to get more than 256 bytes data from the applet in the card!!
    According to JCRE specification, need to use Get Response Command.
    What is Get Response command?
    Do I have to write processing of Get Response command to an applet?
    Or JCRE processes Get Response command?
    If knows, please tell me about!!
    Thanks.

    Thanks for your response!!
    I understand that I have to write processing of Get Response command to an applet.
    But case of Schlumberger 32K card, when host send Get Response command to an applet, card reply 6F-00!?
    I'm investigating now, and it seems that response is returned before applet processes Get Response command(CLA = 00, INS = C0).
    Do JCRE perform the process of Get Response command?

  • How to get a string "yyyyMMdd" into date like MM/dd/yyyy?.

    Hi
    How to get a string "yyyyMMdd" into date like MM/dd/yyyy?. i have used
    SimpleDateFormat.parse but it is giving long value. i want to disply the date
    like MM/dd/yyyy
    thank you

    Do you want the string rearranged or do you want to create an instance of some form of Date class?
    If you want to rearrange the string you could just do it yourself provided you know the date string is going to be of the format yyyyMMdd.
    something like this:
    String newDate = origStr.charAt(4) + origStr.charAt(5) + "/" + origStr.charAt(6) + origStr.charAt(7) + "/" ...etc.

  • Converting String to byte array

    Hi,
    There is a code for converting String to byte array, as follows:
         public byte[] toByteArray(String s)
              char[] c = s.toCharArray();
              int len = c.length;
              byte[] b = new byte[len * 2];
    for ( int i = 0 ; i < len ; i++ )
         b[i * 2] = (byte)(c);
         b[(i * 2) + 1] = (byte)(c[i] >> 8);
    return b;
    But this isn't doing the conversion properly. For example, for the � (euro) symbol, it converts to some other unreadable symbol. Also, same is the case for square brackets. Any idea why this' so? What's wrong with the above code?
    The encoding format is UTF-8.
    Thanks.

    > In fact, I tried with String.getBytes() too, but leads to the same problem, with those specific symbols.
    Did you try the String.getBytes(String charsetName) method?
    Both methods have been around since Java 1.1.
    It's an extremely important skill to learn to read the API and become familiar with the tools you will use to program Java. Java has an extensive set of online documentation that you can even download for your convenience. These "javadocs" are indexed and categorized so you can quickly look up any class or method. Take the time to consult this resource whenever you have a question - you'll find they typically contain very detailed descriptions and possibly some code examples.
    Java� API Specifications
    Java� 1.5 JDK Javadocs
    Best of luck!
    ~

  • How to get alternative strings in list of strings.

    Hi experts,
    how to get alternative strings in list of strings.
    eg
    'country1, italy, country2, india, country3, paris, country4, scottland, country5, rome'
    from the above list i need to fetch all the countries and their names separately.
    like country1, country2, country3, country4, country5
    italy, india, paris, scottland, rome
    i am trying the above one in the below fashion
    SELECT SUBSTR
              ('country1, italy, country2, india, country3, paris, country4, scottland, country5, rome',
               1,
                 INSTR
                    ('country1, italy, country2, india, country3, paris, country4, scottland, country5, rome',
                     1,
                     1
               - 1
      FROM DUAL
    can you please any one help me

    If you want the data to be more stuctured, and useful:
    col col_name for a20
    col col_value for a20
    var inlist VARCHAR2(2000)
    exec :inlist := 'country1, italy, country2, india, country3, paris, country4, scottland, country5, rome';
    exec :inlist := replace(:inlist,' ')
    select max(decode(mod(lvl,2),1,value)) col_name
          ,max(decode(mod(lvl,2),0,value)) col_value
    from   (select substr(:InList,start_pos+1, end_pos-start_pos-1) value
                  ,lvl
            from   (select :InList
                          ,case when level = 1 then
                             0
                           else
                             instr(:InList,',',1,level-1)
                           end start_pos
                           ,case when instr(:InList,',',1,level) = 0
                             then length(:InList)+1
                           else
                             instr(:InList,',',1,level)
                           end   end_pos
                         ,level lvl
                    from   dual
                    connect by level <=length(:InList)-length(replace(:InList,','))+1
    group by ceil(lvl/2)
    order by 1;
    COL_NAME             COL_VALUE
    country1             italy
    country2             india
    country3             paris
    country4             scottland
    country5             rome
    Untested on 10g
    Then you could stragg the rows together ...

  • How to get the length in bytes of a string

    My string has both latin (1 byte) and chinese (2 bytes).
    My program is in unicode system.
    How to measure the length in bytes of the string?
    the xlen function does not work.

    Hello,
    parameters : p_str type string.
    data : len type i.
    len = strlen( p_str ).
    write : / len.
    With Regards,
    BVS
    Hi BSV, your code return the number of characters not bytes.
    Remember chinese character in US are encoded with 2 bytes.
    And my string contain both latin and chinese characters.
    thanks

  • How to get the values of an Array using JSP Tags

    Hey guys,
    I need some help. I've splited a String using
    fn:split(String, delim) where String = "1,2,3,4" and delim is ,
    This method returns an Array of splited Strings. how do i get the values from this array using jsp tags. I don't wanna put java code to achive that.
    Any help would be highly appreciated
    Thanks

    The JSTL forEach tag.
    In fact if all you want to do is iterate over the comma separated list, the forEach tag supports that without having to use the split function.
    <c:set var="list" value="1,2,3,4"/>
    <c:forEach var="num" items="${list}">
      <c:out value="${num}"/>
    </c:forEach>The c:forTokens method will let you do this with delimiters other than a comma, but the forEach tag works well just with the comma-delimited string.

  • How to get the number of bytes stored in a field?

    Hi Guys,
    How can i get the number of bytes stored in a field.
    I tried using DESCRIBE FIELD, But here i am getting the length from the definition.
    i.e 8 bytes for string and for character value is from definition.
    Prompt replies will be Awarded with full points:-)
    Thanks,
    vinod.

    u see this : http://help.sap.com/saphelp_nw04/helpdata/en/cf/21f2e5446011d189700000e8322d00/frameset.htm
    http://help.sap.com/saphelp_nw04/helpdata/en/cf/21f2e5446011d189700000e8322d00/frameset.htm
    Madhavi

  • How to load and display a byte array (jpeg) image file dynamically in Flex?

    My web service client (servlet) received a binary jpeg data from an Image Server. The Flex application invokes the
    servlet via HttpService and receives the binary jpeg data as byte array.  How could it be displayed dynamically
    without writing the byte array to a jpeg file?  Please help (some sample code is very much appreciated).

    JPEGEncoder is only useful for converting BitmapData to ByteArray, not the other way around.
    By the way JPEGEncoder and PNGEncoder are part of the Flex SDK now, so no need to use AS3Lib (alltough it's a good library to have around).
    To display/use a ByteArray as image, use a Loader instance with the loadBytes method.
        Loader.loadBytes(bytes:ByteArray, context:LoaderContext = null);
    Listen for the complete event on the Loader.contentLoaderInfo and get the BitmapData in the event handler.
    private function loadJpeg():void {
        var loader:Loader = new Loader();
        loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loaderCompleteHandler);
        //jpgBA is the ByteArray loaded from webservice
        loader.loadBytes(jpgBA);
    private function loaderCompleteHandler(evt:Event):void {
        var t:LoaderInfo = evt.currentTarget as LoaderInfo;
        // display the jpeg in an Image component
        img.source = t.content;
    <mx:Image id="img" scaleContent="false" />

  • From MD5-string to byte array

    Hi fellows, I'm writing a simple cracker for MD5. The hash value has to be passed at command line as argument.
    e.g.
    java Cracker 0cc175b9c0f1b6a831c399e269772661In order to decode the hash value I'm using a brute force approach: therefore I compare a series of strings with the hash value by using the method of the class MessageDigest isEqual(byte[] a, byte[] b). So I encode each string and compare the byte array I get with the byte array of the hash value.
    Here it comes the trouble I'm in:
    when I try to get a bytes array of the MD5 hash value passed as argument of the program , I do get something, but it's not something that the isEqual method of MessageDigest can use to compare. As a result any attempt during the execution of brute force fails, even though the key is one of the string being checked.
    Perhaps am I facing a format problem? Any idea?
    Sorry for my english, it's not my first language
    Thanks to whoever will help

    Almost all questions in these forums about brute force attack on MD5 (or SHA1 or SHA256 etc etc etc) are school, college or university projects and of no practical use. This is almost certainly such a project.
    Unless things have changed in the last year, there is no practical brute force attack on MD5 whereby an input can be generated from an arbitrary output even though two inputs with the same output can be fabricated. A dictionary attack is feasible if no salt is used or a known salt is used since one only has to build the dictionary for one salt value. If a different salt is used for each entry being attacked then a dictionary will be need for each salt being used. Of course if one takes the simple precaution of not using anything that is likely to be in a dictionary then the dictionary attack will likely fail.

  • How does flatten to string work with arrays?

    Hi all,
    I'm currently trying to get my head around how flatten to string works in terms of using it to write a configuration file which is loaded on startup in my VI. Writing and loading the configuration file is no problem and it is working beautifully. However... this is for a data acquisition system and the configuration file stores all the calibration data in the system which is entered through arrays. Anyway, the data recorded by my VI is to be post processed using MATLAB and needs to apply the calibration data stored in the configuration file.
    So I've been trying to work out how to get MATLAB to decypher the configuration file, but... I can't make heads or tails as to how the data is written into the file. I made a mock up of the saving file routine as you can see below, and run it a number of times by changing the input array dimensions and the values.
    Then opened the saved file to see if I can find a pattern... but I can't! Simply changing the element values changes the number of "\   \'s" Here is what I produced from my trials:
    [1x1 0]
    Config=\00\00\00\01\00\00\00\00\00\00\00\00      (1x1 array of 0's)
    [1x1 1]
    Config=\00\00\00\01?ð\00\00\00\00\00\00            (1x1 array of 1's)
    [1x1 2]
    Config=\00\00\00\01@\00\00\00\00\00\00\00       (1x1 array of 2's)
    [1x2 0]
    Config=\00\00\00\02\00\00\00\00\00\00\00\00\00\00\​00\00\00\00\00\00      (1x2 array of 0's)
    [1x2 1]
    Config=\00\00\00\02?ð\00\00\00\00\00\00?ð\00\00\00​\00\00\00                  (1x2 array of 1's)
    [1x2 2]
    Config=\00\00\00\02?ð\00\00\00\00\00\00?ð\00\00\00​\00\00\00                  (1x2 array of 2's) etc. etc. etc
    [2x2 0]
    Config=\00\00\00\02\00\00\00\02\00\00\00\00\00\00\​00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00​\00\00\00\00\00\00\00\00\00     
    [2x2 1]
    Config=\00\00\00\02\00\00\00\02?ð\00\00\00\00\00\0​0?ð\00\00\00\00\00\00?ð\00\00\00\00\00\00?ð\00\00\​00\00\00\00
    [2x2 2]
    Config=\00\00\00\02\00\00\00\02@\00\00\00\00\00\00​\00@\00\00\00\00\00\00\00@\00\00\00\00\00\00\00@\0​0\00\00\00\00\00\00
    Could someone explain to me how flatten to string flattens the array information? Particularly when the array elements are double precision? I look forward to any help that anyone can offer!
    Thanks,
    Stirling
    Message Edited by stirlsilver on 09-08-2007 08:47 AM
    Attachments:
    saveconfig.png ‏7 KB

    There are optional inputs to "flatten to string" That you can use to modify the outcome as needed. For example you can do little endian.
    You can also omit the array size from the flattened data (definitely not recommended for 2D arrays).
    LabVIEW Champion . Do more with less code and in less time .

  • How can i convert object to byte array very*100 fast?

    i need to transfer a object by datagram packet in embeded system.
    i make a code fallowing sequence.
    1) convert object to byte array ( i append object attribute to byte[] sequencailly )
    2) send the byte array by datagram packet ( by JNI )
    but, it's not satisfied my requirement.
    it must be finished in 1ms.
    but, converting is spending 2ms.
    network speed is not bottleneck. ( transfer time is 0.3ms and packet size is 4096 bytes )
    Using ObjectOutputStream is very slow, so i'm using this way.
    is there antoher way? or how can i improve?
    Edited by: JongpilKim on May 17, 2009 10:48 PM
    Edited by: JongpilKim on May 17, 2009 10:51 PM
    Edited by: JongpilKim on May 17, 2009 10:53 PM

    thanks a lot for your reply.
    now, i use udp socket for communication, but, i must use hardware pci communication later.
    so, i wrap the communication logic to use jni.
    for convert a object to byte array,
    i used ObjectInputStream before, but it was so slow.
    so, i change the implementation to use byte array directly, like ByteBuffer.
    ex)
    public class ByteArrayHelper {
    private byte[] buf = new byte[1024];
    int idx = 0;
    public void putInt(int val){
    buf[idx++] = (byte)(val & 0xff);
    buf[idx++] = (byte)((val>>8) & 0xff);
    buf[idx++] = (byte)((val>>16) & 0xff);
    buf[idx++] = (byte)((val>>24) & 0xff);
    public void putDouble(double val){ .... }
    public void putFloat(float val){ ... }
    public byte[] toByteArray(){ return this.buf; }
    public class PacketData {
    priavte int a;
    private int b;
    public byte[] getByteArray(){
    ByteArrayHelper helper = new ByteArrayHelper();
    helper.putInt(a);
    helper.putInt(b);
    return helper.toByteArray();
    but, it's not enough.
    is there another way to send a object data?
    in java language, i can't access memory directly.
    in c language, if i use struct, i can send struct data to copy memory by socket and it's very fast.
    Edited by: JongpilKim on May 18, 2009 5:26 PM

  • How to get folder size in bytes

    Hi all,
    Is there a easy way to get folder size in bytes?  I don't want to check each file in it and then add them up.
    Thanks for any help.
    Anne

    Years ago, I found my home PC was lacking disk space and could not exaplain where all of the space went.
    At the same time I was teaching myslef how to use the Picture control and Windows did not allow you to check the size of a folder and it sub-folders. So I used that situation to learn about the picture control and LV at the same time.
    It worked and ran but very slowly.
    Soon after Greg McKaskle was putting together the first version of "The Good The Bad and The Ugly" and was looking for fodder to beat up. I offered and he accepted. When the time came for the presentation, my code was chosen as "The bad" since I had not learned how to do a cluster sort at that time so I wrote my own version of a bubble sort (the VI presents a Pie Chart of disk usage and clcik on the sectors of the Pie Chart allowed you to drill down so I hd to sort by sizes).
    So why am I telling you this long boring story?
    That code is attached for you to look at laugh and tell me how dumb I was.
    Feel free to beat me up. It can't be any worse than the abuse I got from Greg (I felt like I was being raped).
    Have fun!
    Ben
    Code is probably 6 or thereabouts. "Disk_Utility" is top level. Remember this is an example of how NOT to code.
    Ben Rayner
    I am currently active on.. MainStream Preppers
    Rayner's Ridge is under construction
    Attachments:
    DIsk_Pie_Utility.zip ‏162 KB

Maybe you are looking for