Java image and byte[]

I am having trouble writing and reading data from an image. I am using the following code to get the bytes for a picture.
BufferedImage pic = ImageIO.read(new File(picture));
WritableRaster writableRaster = pic.getRaster();
DataBufferByte buffer = (DataBufferByte)writableRaster.getDataBuffer();
byte[] picBytes = buffer.getData();After making some changes I would like to write the new bytes to a file. This seems to work as the new picture shows the changes when I look at it.
File newFile = new File("C:/NewPic.jpg");
ImageIO.write(pic,"jpg",newFile);However, when I try to read the newFile using the same method as above I do not get the same bytes. I am using the following code to print the bytes in hex to verify what they are.
BufferedWriter out2 = new BufferedWriter(new FileWriter("pix2.txt"));
for(int x=0; x<picBytes.length; x++)
out2.write((Integer.toString(picBytes[x] & 0xff, 16).toUpperCase()+" "));
}This produces:
7F 7F 7F 7F 7F 7F 7F 7F 7F 7F 7F 7F 7F 7F 7F 7F
7F 7F 7F 7F 7F 7F 7F 7F 7F 7F FF FF 7F FF FF FF
for the bytes that I have made the changes to, and when I try to read from the newly created file I get:
82 7F 7A 82 7F 7A 82 7E 7D 82 7E 7D 82 7D 7F 82
7D 7F 82 7B 82 82 7B 82 AC A5 AC B4 AE B3 E0 DA
but there is nothing wrong with the picture. Do I need to create a new BufferedImage before I save, or what could be causing this change?

Hmmm... I'm not sure what you are doing or what your goal is, but are you aware that JPEGs tend to use a losey compression?

Similar Messages

  • Re: Java Images and Threads prob Help!!

    Without going through it in detail the problem may be that you're doing the repaint which you hope will draw the image before the image has completed loading.
    Create your ImageIcon (loading the "xxxx.jpeg" files) during program initialisation. And check the load status of the icon, at least in a test version.

    I still cant get the reqd output. Only the 1st image is dispayed and when i click the second code, the 2nd image doesnt come(the first one does not disappear, and even when i click the code 1 i have to minimize/ maximize the screen, to get the image and after that it does not go for the s2nd image 2 come!! )
    Create your ImageIcon (loading the "xxxx.jpeg" files) during program >>initialisation. And check the load status of the icon, at least in a test version. How do u load the image during initialization??? and can ny1 plz tell me how to get the flashing threads with msgs????

  • A good book or a Tutorial about java Imaging

    Hello. I am new to java imaging and i was wondering if there is a good book or e-book or a tutorial that can help me learn about image processing. Do you have any suggestions? Thanx

    You can try this link ....
    hope it will help u a lot....
    http://www.javalobby.org/articles/ultimate-image/

  • Images, Thumbnails, byte[ ] and BLOB

    Hi guys,
    This is what I have to do:
    User selects image from disk and i'm putting it into DB (IBM DB2 8.0). That's clear. No problem.
    But I need that image as a thumbnail as well (I have to show images as thumbnails for each Item). I have a DB table IMAGE with 2 columns - IMAGE_FULL and IMAGE_THUMBNAIL.
    So I need to scale image(wich I have as byte array, or struts FormFile) and than put it into DB as Thumbnail.
    Or even if I don't have IMAGE_THUMBNAIL column, I have to get image as byte array from IMAGE_FULL column, scale it and show it in the browser.
    So, if I explained correctly and not very complicated way, can anyone give some ideas?
    Thanks in advance
    Gio

    For thumbnails, there's plenty of examples of resizing and saving images in the Java Programming forum, just do a search.
    For the database storage and retrieval... I had found some really good site with database examples, but I can't find it anymore.... but here's some code:
    // store
                   PreparedStatement pstmt = db.getConnection().prepareStatement(
                        "INSERT INTO TeeColor VALUES( ?, ? )" );
                   pstmt.setString(1, "yellow");
                   File fImage = new File("yellow.gif");
                   InputStream isImage = new FileInputStream(fImage);
                   pstmt.setBinaryStream(2, isImage, (int)fImage.length());
                   int res = pstmt.executeUpdate();
    // load
                   Statement stmt = db.getConnection().createStatement();
                   ResultSet rs = stmt.executeQuery(
                        "SELECT TCBlob FROM TeeColor WHERE TColor = 'Yellow'");
                   if(rs.next()) {
                        byte[] bytes = rs.getBytes("TCBlob");
                        JFrame f = new JFrame("test");
                        f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                        f.getContentPane().add(new JLabel(new ImageIcon(bytes)));
                        f.pack();
                        f.show();
                   }

  • Downloading images and audio file using java

    Dear All
    I have a directory on my webserver which contains images,audio files and many other data files.
    I want to download all the file but the problem is when i download image and save it, it is not viewable. I dont want to use Image class as i may have to downlaod audio files too. Please guis which stream shouldi open to download any kind of content using same code.
    Thanks in advance. And if u have some example please let me know
    Regards
    Jafery

    downloading images and audio file using java -------------------------------
    how to write it back to dataoutputstremI don't understand what you are talking about.
    Server: DataOutputStream -> Client: DataInputStream -- the two is a pair.

  • How to change the image into byte and byte array into image

    now i am developing one project. i want change the image into byte array and then byte array into image.

    FileInputStream is = new FileInputStream(file);
    byte[] result = IOUtils.toByteArray(is);
    with apache common IO lib

  • Where can I download the last version that allows images and java script to be turned off?

    Due to my often slow connection I must have the option to turn off "automatically download images" and Java script. Firefox 23 does not have those options. Where can I download version 22 or whatever the latest version is that allowed these options?
    Thanks

    The Quickimage add-on doesn't work well at all, it gets stuck in the image off mode and will not switch back even after rebooting Firefox. Version 23.0 of Firefox is also very slow on my computer.
    I really need to find an older version of Firefox. Any idea where to download version 22 or earlier?

  • How to display URL images and URL link (html) from Smartforms?

    Hi Gurus,
    I'm having difficulty on how to display targeted URL images and URL link from the smartforms, after i sending it out as html mail. The mail i sent just can be preview as a plain text, which can't execute the html code that i put inside the smartforms itself. I follow a few step from this very useful blog.. Hopefully, you guys can give me some solutions or ideas on this.
    /people/pavan.bayyapu/blog/2005/08/30/sending-html-email-from-sap-crmerp -thanks to Pavan for his useful blog.
    My code is like this..
    <--- Start Code.
    FORM call_smartforms.
      DATA : lv_subject TYPE so_obj_des,
             lc_true(1) VALUE 'X',
             lw_control_parameters TYPE ssfctrlop,
             lw_output_options TYPE ssfcompop,
             lc_graphics(8) VALUE 'GRAPHICS',
             lw_xsfparam_line TYPE ssfxsfp,
             lc_extract(7) VALUE 'EXTRACT',
             lc_graphics_directory(18) VALUE 'GRAPHICS-DIRECTORY',
             lc_mygraphics(11) VALUE 'mygraphics/',
             lc_content_id(10) VALUE 'CONTENT-ID',
             lc_enable(6) VALUE 'ENABLE',
             lw_job_output_info TYPE ssfcrescl,
             lw_html_data TYPE trfresult,
             lw_graphics TYPE ssf_xsf_gr,
             lt_graphics TYPE tsf_xsf_gr,
             lv_html_xstr TYPE xstring,
             lw_html_raw LIKE LINE OF lw_html_data-content,
             lv_incode TYPE tcp00-cpcodepage VALUE '4110',
             lv_html_str TYPE string,
             lv_html_len TYPE i,
             lc_utf8(5) VALUE 'utf-8',
             lc_latin1(6) VALUE 'latin1',
             lv_offset TYPE i,
             lv_length TYPE i,
             lv_diff TYPE i,
             lt_soli TYPE soli_tab,
             lw_soli TYPE soli,
             lc_mime_helper TYPE REF TO cl_gbt_multirelated_service,
             lv_name TYPE mime_text VALUE 'sapwebform.htm',
             lv_xstr TYPE xstring,
             lw_raw TYPE bapiconten,
             lt_solix TYPE solix_tab,
             lw_solix TYPE solix,
             lv_filename TYPE string,
             lv_content_id TYPE string,
             lv_content_type TYPE w3conttype,
             lv_obj_len TYPE so_obj_len,
             lv_bmp TYPE so_fileext VALUE 'BMP',
             lv_description TYPE so_obj_des VALUE 'Graphic in BMP format',
             lc_doc_bcs TYPE REF TO cl_document_bcs,
             lc_bcs TYPE REF TO cl_bcs,
             lc_send_exception TYPE REF TO cx_root,
             lw_adsmtp TYPE lty_adsmtp,
             lv_mail_address TYPE ad_smtpadr,
             lc_recipient TYPE REF TO if_recipient_bcs,
             lc_send_request TYPE REF TO cl_bcs,
             lv_sent_to_all TYPE os_boolean.
      DATA : v_language TYPE sflangu VALUE 'E',
             v_e_devtype TYPE rspoptype.
      v_form_name = 'ZTEST_EMAIL'.
      CALL FUNCTION 'SSF_FUNCTION_MODULE_NAME'
        EXPORTING
          formname           = v_form_name
        IMPORTING
          fm_name            = v_namef
        EXCEPTIONS
          no_form            = 1
          no_function_module = 2
          OTHERS             = 3.
      IF sy-subrc = 0.
       break mhusin.
      ENDIF.
    starting here. ***
    Set title for the output
      lv_subject = 'Smartforms.'.
    Set control parameters to "no dialog"
      lw_control_parameters-no_dialog = lc_true.
    IF lw_service_subject-code = lc_fm1.
    *--- To get output device type
      CALL FUNCTION 'SSF_GET_DEVICE_TYPE'
        EXPORTING
          i_language    = v_language
          i_application = 'SAPDEFAULT'
        IMPORTING
          e_devtype     = v_e_devtype.
      lw_output_options-tdprinter = v_e_devtype.
      lw_control_parameters-getotf = 'X'.
      IF sy-subrc = 0.
       break mhusin.
      ENDIF.
    Set output options
      lw_output_options-xsf        = lc_true.
      lw_output_options-xsfcmode   = lc_true.
      lw_output_options-xsfoutmode = 'A'.
      lw_output_options-xsfoutdev  = space.
      lw_output_options-xsfformat  = lc_true.
      lw_xsfparam_line-name  = lc_graphics.
      lw_xsfparam_line-value = lc_extract.
      APPEND lw_xsfparam_line TO lw_output_options-xsfpars.
      lw_xsfparam_line-name  = lc_graphics_directory.
      lw_xsfparam_line-value = lc_mygraphics.
      APPEND lw_xsfparam_line TO lw_output_options-xsfpars.
      lw_xsfparam_line-name  = lc_content_id.
      lw_xsfparam_line-value = lc_enable.
      APPEND lw_xsfparam_line TO lw_output_options-xsfpars.
    Get the smartform content
      CALL FUNCTION v_namef
        EXPORTING
          control_parameters   = lw_control_parameters
          output_options       = lw_output_options
    *pass other application specific parameters (eg order number, items ).
      IMPORTING
          job_output_info    = lw_job_output_info
      TABLES
          tt_tabh              = tt_tabh
          tt_tabb              = tt_tabb
          tt_tabf              = tt_tabf
      EXCEPTIONS
          formatting_error = 1
          internal_error   = 2
          send_error       = 3
          user_canceled    = 4
          OTHERS           = 5.
      IF sy-subrc = 0.
       break mhusin.
      ENDIF.
      lw_html_data  = lw_job_output_info-xmloutput-trfresult.
      lt_graphics[] = lw_job_output_info-xmloutput-xsfgr[].
      CLEAR lv_html_xstr.
      LOOP AT lw_html_data-content INTO lw_html_raw.
        CONCATENATE lv_html_xstr lw_html_raw INTO lv_html_xstr IN BYTE MODE.
      ENDLOOP.
      lv_html_xstr = lv_html_xstr(lw_html_data-length).
      CALL FUNCTION 'SCP_TRANSLATE_CHARS'
        EXPORTING
          inbuff       = lv_html_xstr
          incode       = lv_incode
          csubst       = lc_true
          substc_space = lc_true
        IMPORTING
          outbuff      = lv_html_str
          outused      = lv_html_len
        EXCEPTIONS
          OTHERS       = 1.
    *HACK THE HTML CODE GENERATED BY SMARTFORM TO MAKE THE
    *EXTERNAL IMAGES APPEAR AS <IMG> TAG IN HTML
      REPLACE ALL OCCURRENCES OF '<IMG' IN lv_html_str WITH '<IMG' IGNORING CASE.
      REPLACE ALL OCCURRENCES OF '/>' IN lv_html_str WITH '/>' IGNORING CASE.
      REPLACE ALL OCCURRENCES OF '</A>' IN lv_html_str WITH '' IGNORING CASE.
      REPLACE ALL OCCURRENCES OF '<' IN lv_html_str WITH '<' IGNORING CASE.
      REPLACE ALL OCCURRENCES OF '>' IN lv_html_str WITH '>' IGNORING CASE.
    CALL METHOD html_control - >load_mime_object
       EXPORTING
         object_id  = 'ZWN'
         object_url = 'ZWN.GIF'
       EXCEPTIONS
         OTHERS     = 1.
      REPLACE ALL OCCURRENCES OF lc_utf8 IN lv_html_str WITH lc_latin1.
    REPLACE ALL OCCURRENCES OF lc_utf8 IN lv_html_str WITH 'iso-8859-1'.
       break mhusin.
      lv_html_len = STRLEN( lv_html_str ).
      lv_offset = 0.
      lv_length = 255.
      WHILE lv_offset < lv_html_len.
        lv_diff = lv_html_len - lv_offset.
        IF lv_diff > lv_length.
          lw_soli-line = lv_html_str+lv_offset(lv_length).
        ELSE.
          lw_soli-line = lv_html_str+lv_offset(lv_diff).
        ENDIF.
        APPEND lw_soli TO lt_soli.
        ADD lv_length TO lv_offset.
      ENDWHILE.
      CREATE OBJECT lc_mime_helper.
      CALL METHOD lc_mime_helper->set_main_html
        EXPORTING
          content     = lt_soli
          filename    = lv_name
          description = lv_subject.
      LOOP AT lt_graphics INTO lw_graphics.
        CLEAR lv_xstr.
        LOOP AT lw_graphics-content INTO lw_raw.
          CONCATENATE lv_xstr lw_raw-line INTO lv_xstr IN BYTE MODE.
        ENDLOOP.
        lv_xstr = lv_xstr(lw_graphics-length).
        lv_offset = 0.
        lv_length = 255.
        CLEAR lt_solix[].
        WHILE lv_offset < lw_graphics-length.
          lv_diff = lw_graphics-length - lv_offset.
          IF lv_diff > lv_length.
            lw_solix-line = lv_xstr+lv_offset(lv_length).
          ELSE.
            lw_solix-line = lv_xstr+lv_offset(lv_diff).
          ENDIF.
          APPEND lw_solix TO lt_solix.
          ADD lv_length TO lv_offset.
        ENDWHILE.
        CONCATENATE lc_mygraphics lw_graphics-graphics text-001 INTO lv_filename.
        CONCATENATE lc_mygraphics lw_graphics-graphics text-001 INTO lv_content_id.
        lv_content_type = lw_graphics-httptype.
        lv_obj_len      = lw_graphics-length.
    *Add images to the email
        CALL METHOD lc_mime_helper->add_binary_part
          EXPORTING
            content      = lt_solix
            filename     = lv_filename
            extension    = lv_bmp
            description  = lv_description
            content_type = lv_content_type
            length       = lv_obj_len
            content_id   = lv_content_id.
      ENDLOOP.
      TRY.
          lv_subject = lv_subject.
          lc_doc_bcs = cl_document_bcs=>create_from_multirelated(
                   i_subject          = lv_subject
                   i_multirel_service = lc_mime_helper ).
        CATCH cx_document_bcs INTO lc_send_exception.
        CATCH cx_bcom_mime INTO lc_send_exception.
        CATCH cx_gbt_mime INTO lc_send_exception.
      ENDTRY.
    Create send request
      TRY.
          lc_bcs = cl_bcs=>create_persistent( ).
        CATCH cx_send_req_bcs INTO lc_send_exception.
      ENDTRY.
      TRY.
          lc_bcs->set_document( i_document = lc_doc_bcs ).
        CATCH cx_send_req_bcs INTO lc_send_exception.
      ENDTRY.
    Set-up email receiver
      lv_mail_address = '[email protected]'.
    TRANSLATE lv_mail_address TO UPPER CASE.
      TRY.
          lc_recipient = cl_cam_address_bcs=>create_internet_address(
              i_address_string = lv_mail_address ).
        CATCH cx_address_bcs INTO lc_send_exception.
      ENDTRY.
      TRY.
          lc_bcs->add_recipient( i_recipient = lc_recipient ).
        CATCH cx_send_req_bcs INTO lc_send_exception.
      ENDTRY.
    Send smartforms as HTML email
      TRY.
          lc_bcs->send( ).
        CATCH cx_send_req_bcs INTO lc_send_exception.
      ENDTRY.
      COMMIT WORK.
      WRITE:/ 'Mail sent'.
    ENDFORM.                    "call_smartforms
    End Code --->
    Thanks and Regards.

    1- put your images in a directory under the web app directory. Example: app/images/
    2- in your jsp, use: String file = application.getRealPath("/images/"); to get the images directory. See http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/servlet/ServletContext.html#getRealPath(java.lang.String)
    3- it's not the right forum to post this kind of question. Post them in the JSP/Servlet JSTL forum instead

  • How to Save an image and retreve the same image with edit option!! ???

    I am facing with a problem
    I have a image which is preloaded, user accessing the image should be provided with a option of adding a text on some part of image etc and save it. Later when that imagine is tried and retrived it should display the edited and saved image and allow user to edit again.The text will be written in a square box which can be dragged anywhere on the image. Is java script and ajax best for this.?
    Can anyone help in showing the basic things i need to follow to achieve this.
    Thanks in Advance
    Edited by: aadi on Feb 12, 2008 9:41 PM

    You could try to write a web service that returns a byte array and convert the image to bytes, and convert it back into an image again.

  • Thumbnail images, mysql, byte[ ]  - need some help

    I'm using the tech tip found on sun's site for "Creating Image Thumbnails" at http://java.sun.com/developer/TechTips/1999/tt1021.html#tip1
    I've looked over the code, and now I'm trying to mesh some of the code from that example with the code for my servlet program.
    My servlet takes a jpeg image submitted from an html form on a web page (all of which I'm testing on my localhost Tomcat server) and uploads it into my mysql database into a column of type BLOB. I do not upload a reference to a FILE, rather, I upload the BYTES that make up that image.
    I wanted to make the images into a thumbnail size PRIOR to uploading them into the db.
    My code snippet for my servlet that just uploads the file without modifying its size is:
    boolean isPart = FileUpload.isMultipartContent(req);
         if(isPart)
    DiskFileUpload upload = new DiskFileUpload(); // upload a file from the local disk.
    List items = upload.parseRequest(req); // Create a list of all uploaded files.
         Iterator it = items.iterator(); // Create an iterator to iterate through the list.
              while(it.hasNext())
         FileItem item = (FileItem)it.next();
         File f = new File(item1.getName()); // Create a FileItem object to access the file.
    byte[] bytes = new byte[(int)f.length()];
         FileInputStream fs = new FileInputStream(f);
         BufferedInputStream bis = new BufferedInputStream(fs);
         bis.read(bytes);
    PreparedStatement stmt = conn.prepareStatement("UPDATE car SET Image1 = ? where Account=1");
         stmt.setBytes(1, bytes);
         int i = stmt1.executeUpdate();
    Here is the code from the Tech Tip:
    import java.awt.Image;
    import java.awt.Graphics2D;
    import java.awt.geom.AffineTransform;
    import java.awt.image.BufferedImage;
    import java.io.IOException;
    import java.io.OutputStream;
    import java.io.FileOutputStream;
    import javax.swing.ImageIcon;
    import com.sun.image.codec.jpeg.JPEGCodec;
    import com.sun.image.codec.jpeg.JPEGImageEncoder;
    class Thumbnail {
    public static void main(String[] args) {
    createThumbnail(args[0], args[
    1], Integer.parseInt(args[2]));
    * Reads an image in a file and creates
    * a thumbnail in another file.
    * @param orig The name of image file.
    * @param thumb The name of thumbnail file.
    * Will be created if necessary.
    * @param maxDim The width and height of
    * the thumbnail must
    * be maxDim pixels or less.
    public static void createThumbnail(
    String orig, String thumb, int maxDim) {
    try {
    // Get the image from a file.
    Image inImage = new ImageIcon(
    orig).getImage();
    // Determine the scale.
         double scale = (double)maxDim/(
         double)inImage.getHeight(null);
    if (inImage.getWidth(
    null) > inImage.getHeight(null)) {
    scale = (double)maxDim/(
    double)inImage.getWidth(null);
    // Determine size of new image.
    //One of them
    // should equal maxDim.
    int scaledW = (int)(
    scale*inImage.getWidth(null));
    int scaledH = (int)(
    scale*inImage.getHeight(null));
    // Create an image buffer in
    //which to paint on.
    BufferedImage outImage =
    new BufferedImage(scaledW, scaledH,
    BufferedImage.TYPE_INT_RGB);
    // Set the scale.
    AffineTransform tx =
    new AffineTransform();
    // If the image is smaller than
    //the desired image size,
    // don't bother scaling.
    if (scale < 1.0d) {
    tx.scale(scale, scale);
    // Paint image.
    Graphics2D g2d =
    outImage.createGraphics();
    g2d.drawImage(inImage, tx, null);
    g2d.dispose();
    // JPEG-encode the image
    //and write to file.
    OutputStream os =
    new FileOutputStream(thumb);
    JPEGImageEncoder encoder =
    JPEGCodec.createJPEGEncoder(os);
    encoder.encode(outImage);
    os.close();
    } catch (IOException e) {
    e.printStackTrace();
    System.exit(0);
    I will be changing the following line right off the bat:
    1 ) changing the argument passed to:
    Image inImage = new ImageIcon(bytes);
    I'm passing it my array
    bytes
    which I created in my upload servlet, it's holding the image.
    I don't want to write the newly thumbnail sized image to a JPEG stream as it is coded at the end of the program from Sun.
    Instead, I want to read the newly sized image into a
    byte[ ]
    array and then continue with my servlet program, and place the image into the db. I have a column of type BLOB waiting for it:)
    Does anyone know how to do this?

    Yes I have done this, do not have the code to hand, its in a real mess anyway, one of those things I got working and never got round to using...
    I based my code on some found here
    http://forum.java.sun.com/thread.jspa?forumID=20&threadID=505366
    Note, the above link shows how to add a watermark to an image as well.
    It does not show how to resize it (I was originally after the watermark bit) But I got it to resize by messing with the variables used to draw out the image.
    If you search the forums you will find this a common problem, but I was very impressed with the code posted in the above link, one of my favorites!

  • Create image from byte[]array on server side

    Hello everyone..
    I'm developing an application which will take snapshots from a mobile device, and send it to my pc via bluetooth. I have my own midlet which uses the phone camera to take the snapshot, i want to transfer that snapshot to my pc.
    The snapshot is taken is stored in an array byte.
    The image can be created on the phone itself with no problem using : image.createImage(byte[])
    my problem is that when i send the array byte via bluetooth, and receive it on the server, i cannot create the image using the :image.createImage() code
    The connection is good since i have tested by writing the content of the array in a text file.
    Piece of midlet code:
                try{
                     stream = (StreamConnection)Connector.open(url);
                     OutputStream ggt = stream.openOutputStream();
                     ggt.write(str);
                     ggt.close();
                }catch(Exception e){
                     err1  = e.getMessage();
                }where str is my array byte containing the snapshot
    And on my server side:
    Thread th = new Thread(){
                   public void run(){
                        try{
                             while(true){
                                  byte[] b = new byte[in.read()];
                                  int x=0;
                                  System.out.println("reading");
                                  r = in.read(b,0,b.length);
                                  if (r!=0){
                                       System.out.println(r);     
                                       img = Image.createImage(b, 0, r);
                                                            //other codes
                                       i get this error message:
    Exception in thread "Thread-0" java.lang.UnsatisfiedLinkError: javax.microedition.lcdui.ImmutableImage.decodeImage([BII)V
         at javax.microedition.lcdui.ImmutableImage.decodeImage(Native Method)
         at javax.microedition.lcdui.ImmutableImage.<init>(Image.java:906)
         at javax.microedition.lcdui.Image.createImage(Image.java:367)
         at picserv2$1.run(picserv2.java:70)
    Please anyone can help me here? is this the way to create the image on the server side? thx a lot

    here is exactly how i did it :
    while(true){
                                  byte[] b = new byte[in.read()];
                                  System.out.println("reading");
                                  r = in.read(b, 0, b.length);
                                  if (r!=0){
                                       Toolkit toolkit = Toolkit.getDefaultToolkit();
                                       Image img = toolkit.createImage(b, 0, b.length);
                                       JLabel label = new JLabel(new ImageIcon(img) );
                                       BufferedImage bImage = new BufferedImage(img.getWidth(label),img.getHeight(label),BufferedImage.TYPE_INT_RGB);
                                       bImage.createGraphics().drawImage(img, 0,0,null);
                                       File xd = new File("D:/file.jpg");
                                       ImageIO.write(bImage, "jpg", xd);
                                       System.out.println("image sent");
                             }Edited by: jin_a on Mar 22, 2008 9:58 AM

  • Reading an image in byte form

    hii guys
    i m trying to read an image and convert it to byte array and later to do some change in that byte array and later recreate a new image.
    For that i m using FileInputStream and FileOutputStream and its read and write methods
    but now i dont know how to append that byte and recreate that image.
    actually i want to do that , convert the image in byte array form and replacing some bytes of the image by my text msg bytes and recreate a new image.
    how an i do that.
    plz help me.
    its urgent.

    import java.io.*;
    class image
    public static void main(String[] arg) throws IOException
    String msg;
    int len,i;
    FileInputStream fin;
    FileOutputStream fout;
    try
    try
    fin=new FileInputStream("01.jpg");
    catch( Exception e)
    System.out.println("Input image not found");
    return;
    try
    fout=new FileOutputStream("001.jpg");
    catch( Exception e)
    System.out.println("output image cannt be created");
    return;
    catch(Exception e)
    System.out.println("output image cannt be created");
    return;
    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
    System.out.println("Enter the secret msg :: ");
    msg=br.readLine();
    byte[] msg1=msg.getBytes();
    len=msg1.length;
    System.out.println(len);
    for(i=0;i<len;i++)
    System.out.println(msg1);
    try
    do
    byte by=(byte)fin.read();
    //System.out.print(" "+by);
    if(fin.available()>0)
    fout.write(by);
    }while(fin.available()>0);
    catch(Exception e)
    System.out.println("File error");
    fin.close();
    fout.close();
    till now i only imputed the sg , change it into byte form .
    now i want to replace the msg bytes into the image byte as :- 1 image byte ,1 msg byte, 1 image byte , 1 msg byte........ so on
    until the msg bytes are not finished.

  • Image to byte array

    hello,
    how can i get an image in jar file as a byte[] or can i convert an image to byte[]?
    thx...

    To read a bytes from a jar file, use a JarInputStream. If you're just trying to read bytes from a jar, it doesn't make any difference whether it's an image or not.
    To get the bytes from an Image, you need to put more information in your question - are you talking about an image file, like a JPEG or TIFF? What do you want to do with it? Or are you talking about an Image object in Java? If so, which specific concrete subclass, and what do you want to do with it?

  • How to display images and information

    how to display images and information(e.g. like questions) on a jsp page that stored in a database

    Look As far as i can see....
    Utlimately every file could be expressed as a bytes buffer.
    so say if you have a bean called Choice Bean which is expressed as
    public class ChoiceBean{
       private String choiceid;
       private String choicedesc;
       private byte image[];
       public void setChoiceId(String choiceid){
              this.choiceid = choiceid;
        public String getChoiceId(){
               return this.choiceid;
          public void setChoiceDesc(String choicedesc){
               this.choicedesc = choicedesc;
           public String getChoiceDesc(){
               return this.choicedesc;
           public void setImage(byte image[]){
                  this.image = image;
             public byte[] getImage(){
                  return this.image;
    }QuestionList.java:
    ===============
    public class QuestionList{
         private List<ChoiceBean> choicelist;
          /*Other member variable declarations*/
           public  List<ChoiceBean> getChoiceList(){
                    /*Custom code where you may build the list by querying the DA layer*/
                     return this.choicelist;
         public int search(String choiceid){
                 int index = -1;
                 for(int i =0 ; i < this.choicelist.size() ; i++){
                        ChoiceBean cb = this.choicelist.get(i);
                         if(cb.getChoiceId().equals(choiceid)){
                                index = i;
                                break;
                 return index;
        /* Other member method declarations */
    }and you are retreving List<ChoiceBean> from DB using your query & have created a session attribute / <jsp:useBean> named ChoiceList
    NOTE: sometimes your application server can go out of bounds as you are consuming a lot of memory by creating an arraylist object.
    use the following methodology to display images & choices
    sample.jsp:
    =========
    <jsp:useBean id="QuestionList"  class="com.qpa.dao.QuestionList" scope="session"/>
    <TABLE>
    <%
    /* QuestionList.getChoiceList() is a method which fetches data from the DB & returns it in form of  List<ChoiceBean> */
    List<ChoiceBean> choicelist = QuestionList.getChoiceList();
    for(int i =0 ; i < choicelist.size() ; i++){
    %>
    <TR>
    <TD><%!=choicelist.get(i).getChoiceId()%></TD>
    <!-- calling servlet which renders an images in JPG format based upon given choiceid(unique field) -->
    <TD><IMAGE src="ImageServlet?choiceid=<%!=choicelist.get(i).getChoiceId()%>"/> </TD>
    <TD><%!=choicelist.get(i).getChoiceDesc()%></TD>
    </TR>
    <%
    %>
    </TABLE>
    <%
        session.remove("QuestionList");
    %>
    NOTE: usage of JSTL or any other custom built tag-libraries makes life more simpler in the following case
    ImageServlet.java:
    ===============
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            byte buffer[] = null;
            HttpSession session = request.getSession(false);
            /*getting the QuestionList from the session*/
            QuestionList ql = null;
            String choiceid = new String("");
            try{
                 choiceid = request.getParameter("choiceid");
                 /*getting the QuestionList from the session*/
                ql = (QuestionList)  session.getAttribute("QuestionList");
            } catch(Exception exp){
            if(choiceid.equals("") == false &&  ql != null ){
                List<ChoiceBean> clist = QuestionList.getChoiceList();           
                   assuming that you have created a serach method which searches the entire choice list and would give you
                   the index of that object which is being refered by unique choiceid and returns -1 if not found
                int index =  QuestionList.search(choiceid);
                if(index != -1){
                   ChoiceBean cb = clist.get(index);
                   buffer = cb.getImage();
            if(buffer != null){
                 // assuming that we have stored images in JPEG format only
                 JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(new ByteArrayInputStream(buffer));
                 BufferedImage image =decoder.decodeAsBufferedImage();
                 response.setContentType("image/jpeg");
                 // Send back image
                 ServletOutputStream sos = response.getOutputStream();
                 JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(sos);
                 encoder.encode(image);
            } else {
               response.setContentType("text/html");
               response.getWriter().println("<b>Image data not found</b>");              
    }However,i still feel there are few loopholes with this approach where Application Server can eat up a lot of heap space which may result in outofmemorybound exception.
    Hope this might help :)
    REGARDS,
    RaHuL

  • Get Image's bytes

    Hi people,
    I'm trying to get the bytes from an image. I know the complete path to that image, and I know the image's name also, so I pass the image's whole name as a String to a method wich will read the bytes. When I try to read the image's bytes I get the following meassures: width = -1, height = 0.
    This is the code I use:
      int err = imageReturn(path + "/" + img);
      byte[] b2bytes = b2.toByteArray();
    public int imageReturn(String imagePath){
        //path is c:\javi\image.jpg
        try{
            int w,h;
            Image img = null;
            img = Toolkit.getDefaultToolkit().getImage(imagePath);
            w = img.getWidth(null);
            h = img.getHeight(null);
    System.out.println("image size: " + w + "x" + h); //--> print's -1x0!!!
            BufferedImage finalImage = new BufferedImage(w, h, 
                                                BufferedImage.TYPE_INT_RGB);
            finalImage.createGraphics().drawImage(img, 0, 0, null);
            b2 = new ByteArrayOutputStream(); //global
            JPEGImageEncoder encoder=JPEGCodec.createJPEGEncoder(b2);
            JPEGEncodeParam param=encoder.getDefaultJPEGEncodeParam
                                                               (finalImage);
            param.setQuality(1.0f, false);
            encoder.setJPEGEncodeParam(param);
            encoder.encode(finalImage);
            b2.close();
            return(0);
        }catch(Exception e){
            System.out.println(e.toString());
            return(-1);
    }//imageReturnAs you see, the goal is to get a byte[] with the image information. I don't know if there's any other way (simpler one) to solve it. Any help will be appreciated.
    Thanks all,
    Javi

    The problem really is withe the Image class, which was never intended for this sort of thing. If you use the ImageIO classes, you can get BufferedImages direct from jpg files, and then you have access to the underlying buffers:
    import java.io.*;
    import javax.imageio.*;
    import java.awt.image.*;
    public class FileOperations
        public static BufferedImage readImageFromFile(File file) throws IOException
            return ImageIO.read(file);
        public static void writeImageToFile(File file,BufferedImage bufferedImage) throws IOException
            ImageIO.write(bufferedImage,"JPG",file);
    }

Maybe you are looking for

  • Firefox won't open mailto links in a new window like it used to...it just opens gmail in the current tab.

    I recently upgraded firefox and now whenever I click a mailto link it opens gmail in the current tab rather than in a new window. How can I get it to open email links in a new window.

  • JVM Crash on Linux Cron Restart.

    Our application is deployed in Jboss AS with MySql db under RedHat Linux. We scheduled a cron to restart server on everyday morning. During this time the server is not starting properly, this was not happening regularly. And the log says: # An unexpe

  • Particular web page will not load in safari or firefox

    when i try to load web site www.mapmyride.com, safari will not load the web page. I have tried other web sites and it works fine. It does not give any message to indicate that there's a problem. I can load the same web page on my iphone

  • Problems with Zone based Firewall and mtr (mytraceroute)

    We are using ZFW on an ASR1001 and have experienced a problem: when I try to use mtr (mytraceroute, see http://en.wikipedia.org/wiki/MTR_%28software%29), I am getting packetloss on all hops between the source and the destination. e.g.: <code>        

  • Graphite 1500 Phone / Answer Machine issue

    Hi, Don't know if anyone can help with this please....we had issues with our original graphite machine as it wouldn't record. Having gone through BT support etc they advised us to take it back to the shop and exchange it. We did this, but now the rep