Image file to byte[] to resized image

I have a byte[] that I have recieved from my server, this byte[] is read from an image. I now need to resize it and save it to the users computer as an image again. I have tried to do this, but lost information on the way. For example i tried making it into a BufferedImage, resize that image, and then write it to the computer. This however, caused (for me) very important image information to be lost, such as the jpg image tags. I could save this byte[] directly to the computer as an image and keep the image tags, but then I would have it in the same size. Is there any way for me to resize it before saving it, without losing information?
If it's impossible, please tell me so I know and can start thinking about how to do an alternative solution, however, I think this should be possible.
Edited by: Alle55555 on Jul 16, 2009 2:57 AM

This is my final code for solving the problem:
try
                              //Read the byte[] into an IIOImage
                              ImageReader ir = ImageIO.getImageReadersByFormatName("jpeg").next();
                              ByteArrayInputStream bais = new ByteArrayInputStream(imageBytes.get(viewingIndex));
                              ImageInputStream iis = ImageIO.createImageInputStream(bais);
                              ir.setInput(iis);
                              IIOImage image = new IIOImage(ir.read(0), null, ir.getImageMetadata(0));
                              //Resize the image
                              Image scalingImage = Toolkit.getDefaultToolkit().createImage(imageBytes.get(viewingIndex));
                              double scale = image.getRenderedImage().getWidth()/400;
                              scalingImage = scalingImage.getScaledInstance(400, (int)((double)(image.getRenderedImage().getHeight())/(double)(scale)), Image.SCALE_SMOOTH);
                              MediaTracker medTra = new MediaTracker(this);
                              medTra.addImage(scalingImage, 0);
                              medTra.waitForID(0);
                              BufferedImage bufferedImage = new BufferedImage(scalingImage.getWidth(this), scalingImage.getHeight(this), BufferedImage.TYPE_INT_RGB);
                              Graphics2D g = bufferedImage.createGraphics();
                              g.drawImage(scalingImage, 0, 0, this);
                              image.setRenderedImage(bufferedImage);
                              //Write the IIOImage to a chosen file
                              ImageWriter iw = ImageIO.getImageWritersByFormatName("jpeg").next();
                              ImageOutputStream imageOutputStream;
                              File selectedFile = fileChooser.getSelectedFile();
                              if(selectedFile.getAbsolutePath().endsWith(".jpg") || selectedFile.getAbsolutePath().endsWith(".JPG") || selectedFile.getAbsolutePath().endsWith(".jpeg") || selectedFile.getAbsolutePath().endsWith(".JPEG"))
                                   imageOutputStream = ImageIO.createImageOutputStream(fileChooser.getSelectedFile());
                              else
                                   imageOutputStream = ImageIO.createImageOutputStream(new File(fileChooser.getSelectedFile().getAbsolutePath() + ".jpg"));
                              iw.setOutput(imageOutputStream);
                              iw.write(image.getMetadata(), image, null);
                              imageOutputStream.close();
                         catch (Exception e){e.printStackTrace() ;}

Similar Messages

  • DPT-S1 Feature Add Request: File Size (bytes) Sorting and Display in Documents Lists

    Document Lists view should include option to sort by and display file Size (bytes), as in all other file tools.
    That would permit discovery of duplicate files with different names, and trimming out the largest files to save space.
    Thanks!

    Anyone reading this? Agreeing with me?

  • Converting Files to bytes

    hello
    Just want to know if there anyway to convert a text file to bytes. I can read the textfile but i want to convert them to bytes and store them.

    http://java.sun.com/j2se/1.4.1/docs/api/java/io/InputStream.html
    http://java.sun.com/j2se/1.4.1/docs/api/java/io/OutputStream.html
    Note that the Input[Output]Streams conserve extra byte information other than the content of a text.

  • How to write newline character to file using bytes along with content

    Hi All,
    I need to write headers into the file using byte[]. I am creating the strings of header which will form the different rows in the file. I am new to java and would like to know how to embed new line character so that when the byte[] is written to file headers come in different rows.
    like
    hrd1:abcd
    hdr2:1234
    when i embed \n and \r in string and do getBytes() and write it to file, some boxes are written in the file and everything comes into single line.
    Please advice me the correct way .
    Thanks in advance.
    Cheers!!
    Puneet

    not sure about it, but i was always told that "\r\n" meant "new line" on "lots of documents" whereas "\n" only or "\r" only were meaningless on some type of documents

  • "process mutiple files" freezes computer when resizing images.PSE3

    This function has always worked perfectly for me for years. It started about 2 weeks ago and I have no clue why it is doing this.
    Whenever I try to resize a folder containing mutiple or even single images, it freezes the program and computer until I restart everything.
    More specifics;
    files are being downsized not upsized.
    the original image loads into the program, then as it is being resized, it freezes up at the same point each time. This is when the "progress bar" (not sure of exact name) at the bottom of the page shows about 25% progress.
    I have cleaned up the hard drive and done a file reorganization.
    I have uninstalled and reinstalled the program.
    I can resize images directly through the image/resize function one at a time. The problem is that I frequently have to resize large batches of images.
    Thanks for any help.
    Dave

    Dave
    This has caught other people. Check you Resize Image box to see if some strange value has been entered. One user had accidentally entered 4 pixels instead of 4 inches so all his pictures came out really small. I wonder if you have the opposite problem and are resaving to some extremely large size that Elements does not like.
    If not post back.
    Additional question-are you having problems with the same set of pictures? If so, could you run a test on a second set of pictures. Perhaps there is something strange in the source files.

  • How do I read directly from file into byte array

    I am reading an image from a file into a BuffertedImage then writing it out again into an array of bytes which I store and use later on in the program. Currently Im doing this in two stages is there a way to do it it one go to speed things up.
    try
                //Read File Contents into a Buffered Image
                /** BUG 4705399: There was a problem with some jpegs taking ages to load turns out to be
                 * (at least partially) a problem with non-standard colour models, which is why we set the
                 * destination colour model. The side effect should be standard colour model in subsequent reading.
                BufferedImage bi = null;
                ImageReader ir = null;
                ImageInputStream stream =  ImageIO.createImageInputStream(new File(path));
                final Iterator i = ImageIO.getImageReaders(stream);
                if (i.hasNext())
                    ir = (ImageReader) i.next();
                    ir.setInput(stream);
                    ImageReadParam param = ir.getDefaultReadParam();
                    ImageTypeSpecifier typeToUse = null;
                    for (Iterator i2 = ir.getImageTypes(0); i2.hasNext();)
                        ImageTypeSpecifier type = (ImageTypeSpecifier) i2.next();
                        if (type.getColorModel().getColorSpace().isCS_sRGB())
                            typeToUse = type;
                    if (typeToUse != null)
                        param.setDestinationType(typeToUse);
                    bi = ir.read(0, param);
                    //ir.dispose(); seem to reference this in write
                    //stream.close();
                //Write Buffered Image to Byte ArrayOutput Stream
                if (bi != null)
                    //Convert to byte array
                    final ByteArrayOutputStream output = new ByteArrayOutputStream();
                    //Try and find corresponding writer for reader but if not possible
                    //we use JPG (which is always installed) instead.
                    final ImageWriter iw = ImageIO.getImageWriter(ir);
                    if (iw != null)
                        if (ImageIO.write(bi, ir.getFormatName(), new DataOutputStream(output)) == false)
                            MainWindow.logger.warning("Unable to Write Image");
                    else
                        if (ImageIO.write(bi, "JPG", new DataOutputStream(output)) == false)
                            MainWindow.logger.warning("Warning Unable to Write Image as JPEG");
                    //Add to image list
                    final byte[] imageData = output.toByteArray();
                    Images.addImage(imageData);
                  

    If you don't need to manipulate the image in any way I would suggest you just read the image file directly into a byte array (without ImageReader) and then create the BufferedImage from that byte array.

  • Imported PSD Files Are Being Erroneously Resized in Captivate 4

    I am trying to import PSD files to use in my Captivate 4 project. I verified that the PSD image size is 800 x 600, and my Captivate project dimensions are the same 800 x 600. But when the import process completes, the layers are erroneously resized to smaller dimensions. I have tried the same thing on two separate installations of Captivate 4 on two separate PC's with the same results.
    Here is a screenshot of the PSD file in Photoshop (image size = 800 x 600):
    Now here is a screenshot of what the imported PSD file looks like in the Captivate project (screen size set to 800 x 600):
    When I do the import, I'm selecting: File --> Import --> Photoshop File..., then I select the "As Layers" option, and do not check the box next to "Scale according to stage size" (I have tried using this option as well with the same results, although I don't believe I should have to rescale when the PSD image size and Captivate project size are the same.)
    Any help with this would be greatly appreciated.

    Thanks so much for such a prompt reply...the single .psd file with many layers is imported using:
    Import Kind: Composition
    Layer Options: Editable Layer Styles; Life Photoshop 3D (although there are no 3D layers in the .psd...so I'm unsure if this default is needed?)
    Oh!!  Never mind...I just tried Import Kind: Composition -- Cropped Layers and the layers were not cropped...kind of counter-intuitive since I would have thought "Cropped Layers" would crop the layers rather than the other way around. 
    Thanks for your help...if you just reply to this post I'll mark your reply as the answer, thanks for suggesting the direction to look for a solution, cheers!

  • How to create PNG file from byte array of RGB value?

    Hi
    Here is my problem.
    I have drawn some sketchs (through code in runtime) on canvas. I have grabbed the RGB information for the drwan image and converted to byte array.
    I have to pass this byte array to server and generate a png file and save.
    Please help.

    {color:#ff0000}Cross posted{color}
    http://forum.java.sun.com/thread.jspa?threadID=5218093
    {color:#000080}Cross posting is rude.
    db{color}

  • How to store a mid file in byte[ ]

    I used this method to store the song but it does not seem to be working.
    public byte[] getSongAs_ByteArray() {
        byte[] data = new byte[50848];
        InputStream in = null;
        try {
          HttpConnection connection = null;
          Connector.open("http://www.ziyaaf.com/XML/girl.mid ");
          connection = (HttpConnection) Connector.open(
              " http://www.ziyaaf.com/XML/girl.mid");
              in = connection.openInputStream();
               DataInputStream dis = new DataInputStream(in);
          dis.readFully(data);
          in.close();
        catch (IOException ex) {
          System.out.println("::" + ex);
        return data;
    But if i use this method it works
    public byte[] loadSong() {
        byte[] data = new byte[50848];
        try {
          Class c = this.getClass();
          InputStream is = c.getResourceAsStream(" girl.mid");
          DataInputStream dis = new DataInputStream(is);
          dis.readFully(data);
          is.close();
        catch (IOException ioe) {
          ioe.printStackTrace();
        return data;
    But i want to load the song from a remote location
    And this is the method i used to play the mid file.
    ByteArrayInputStream b = new ByteArrayInputStream(getSongAs_ByteArray());
        try {
          player = Manager.createPlayer(b,
                                        "audio/midi");
          player.start();
        }

    onnector.open("http://www.ziyaaf.com/XML/girl.mid
    connection = (HttpConnection) Connector.open(
    " http://www.ziyaaf.com/XML/girl.mid");
    Firstly, you call open twice, you don't check for http errors, and on the first URL you have a space after the ".mid", and on the second URL your have a space before "http".
    And never ever use fixed size byte arrays!
    And why load the midi file in memory when you can play it directly from stream (specially if you read from file)?

  • Output says "The number of bytes in the file are 0" but the file has bytes

    Dear Java People,
    Why would an output say a file has 0 bytes when upon doing a search for the file in Windows Explorer it say the file has 1 -4 kbytes ?
    for example part of my output was :
    "the number of bytes in TryFile3.java are 0"
    caused by the following lines of code:
    System.out.println("\n" + contents[i] + " is a " +
    (contents.isDirectory() ? "directory" : "file\n") +
    " last modified on " + new Date(contents[i].lastModified())
    + "\nthe number of bytes in TryFile.java are " + myFile.length());
    thank you in advance
    below are the two program classes
    Norman
    import java.io.File;
    import java.io.FilenameFilter;
    import java.util.Date;
    public class TryFile3
       public static void main(String[] args)
           //create an object that is a directory
             File myDir =
            new File("C:\\Documents and Settings\\Gateway User\\jbproject\\stan_ch9p369");
              File myFile = new File(myDir, "TryFile3.java");
            System.out.println("\n" + myDir + (myDir.isDirectory() ? " is" : " is not")
            + " a directory.");
             System.out.println( myDir.getAbsolutePath() +
             (myDir.isDirectory() ? " is" : " is not") + " a directory.");
              System.out.println("The parent of " + myDir.getName() + " is " +
              myDir.getParent());
               //Define a filter for java source files Beginning with the letter 'F'
               FilenameFilter select = new FileListFilter("F", "java");
               //get the contents of the directory
               File[] contents = myDir.listFiles(select);
                //list the contents of the directory
             if(contents != null)
                 System.out.println("\nThe " + contents.length  +
                 " matching item(s) in the directory " + myDir.getName() + " are:\n " );
                 for(int i = 0; i < contents.length; i++)
                   System.out.println("\n" +  contents[i] + " is a " +
                   (contents.isDirectory() ? "directory" : "file\n") +
    " last modified on " + new Date(contents[i].lastModified())
    + "\nthe number of bytes in TryFile3.java are " + myFile.length());
    else {
    System.out.println(myDir.getName() + " is not a directory");
    System.exit(0);
    import java.io.File;
    import java.io.FilenameFilter;
    import java.util.Date;
    public class FileListFilter implements FilenameFilter
    private String name; // file name filter
    private String extension; // File extension filter
    public FileListFilter(String name, String extension)
    this.name = name;
    this.extension = extension;
    // static boolean firstTime = true;
    public boolean accept(File diretory, String filename)
    //the following line of code can be inserted in order to find out who called the method
    // if(firstTime)
    // new Throwable("starting the accept() method").printStackTrace();
    boolean fileOK = true;
    //if there is a name filter specified, check the file name
    if(name != null)
    fileOK &= filename.startsWith(name);
    //if there is an extension filter, check the file extension
    if(extension != null)
    fileOK &= filename.endsWith('.' + extension);
    return fileOK;

    System.out.println("\n" + contents + " is a " +
    (contents.isDirectory() ? "directory" : "file\n") +
    " last modified on " + new Date(contents.lastModified())
    + "\nthe number of bytes in TryFile.java are " + myFile.length());I haven't read any of your italicized code, but perhaps there is a good reason why you have "myFile.length()" and not "contents.length()" in this line of code?

  • Reading file in bytes using FileReader...

    Hi,
    I am trying to read out bytes value from a .bmp file then i try to change the byte values that i read out to hexadecimal value.
    I open the .bmp in Win Hex (a software) but the hexadecimal value does not tally....
    public void readByteFile (String path)
    Vector in = new Vector ();
    try
    FileReader reader = new FileReader (path);
    int c;
    while ((c = reader.read ()) != -1)
    String hex = Integer.toHexString (c);
    reader.close ();
    } catch (FileNotFoundException e) {System.err.println(e);}
    catch (IOException e) {System.err.println(e);}
              return in;
         }

    If you want to read the actual bytes from the file then do not use a Reader. That will convert the bytes to characters as if they were text. Use an InputStream instead.

  • Binary file read byte unmatch

    I tried to read one line of binary file as the top of the screenshot.
    The result is as the left side. It shows the first part with text are correct. The ending part is not match with the raw one.
    I also tried read by byte, but still the same.
    Any suggestion, thanks.
    Solved!
    Go to Solution.
    Attachments:
    shot.JPG ‏48 KB

    What program created this binary file?
    If you can figure out how the file was created, then you can figure out how to read it.
    We can't help because all you've shown are some bytes and say that some are right and some are wrong.  What is the "raw one" you are referring to?  What do you expect it to look like?
    Message Edited by Ravens Fan on 01-26-2010 11:15 PM

  • If reading file as bytes (DataInputStream), how find delimiter?

    I have to read a file in as a DataInputStream because it is really two files (one text, one can be a .doc, .jpg, etc) mixed into one. The files are separated by a delimiter which is something like: "--34f5s--a23--34d--". The binary file data is also ended by that delimiter as well. So how would I find the delimiters while not converting the byte stream and losing data?

    You're probably not going to like this suggestion...
    The only way I can think of off the top of my head is to get the byte array representation of the delimiter, and as each byte passes through your InputStream, compare it with the delimiter array, finite-state-machine-style.
    Send the data on if it doesn't match, otherwise keep matching against the delimiter. If you match halfway and the mismatch, send on the bytes that matched as well as the last byte which didn't. If you match to the end of the delimiter, then the first file is (should be) exactly what you sent on.
    Alternatively, assuming this is for a MIME-style attachment, is there anything in javax.mail that would do this for you? Or another third-party library?

  • Reading file containing byte data

    I am trying to read a file containing data that is in byte format. I can't look at the file and have no idea what is in there. For my first pass I would just like to see what the format is of the data in characters. Is there an easy way to do this? This is what I have done so far:
    //file is read from another method and is passed in here.
    try {
    BufferedReader f = new BufferedReader(new FileReader(file));
    String t;
    while ((t = f.readLine()) != null) {
    byte b[] = t.getBytes();
    System.out.println("bytes " + b[0]);
    System.out.println("chars " + (char)b[0]);
    catch(Exception e) {
    e.printStackTrace();
    The output is looking like this:
    bytes 72
    chars H
    bytes 74
    chars J
    bytes 81
    chars Q
    bytes -56
    chars ?
    Which one is the character value of the bytes? I am assuming the char one, but it sure seems like funny values. Also, I want to read the whole line and then get the whole line converted, not just the first byte. Isn't getBytes just getting the first byte? How can I convert the whole line after it is read (f.readLine())?
    Thanks.
    Allyson

    Well, I tried that and it still gives me just the binary or byte data (I have no idea what kind it is - I know I can't read it when I try to open it with notepad). There is a current application that uses this file and opens it and provides the data when it is opened. I am trying to look thru that code to find out what it does, but it is very confusing. It is written in c.
    Any other ideas out there as to how to open and display the correct data in a file like this? When I did the binary data open this is the kind of data I got:
    char in new loop Q
    char in new loop
    char in new loop @
    char in new loop
    char in new loop @
    char in new loop @
    char in new loop
    char in new loop
    char in new loop @
    char in new loop L
    char in new loop `
    char in new loop :
    char in new loop @
    I know that data is mostly numbers and maybe a few names, but nothing like that.
    Thanks.
    Allyson

  • Sequence File Hierarchy Sequence Name Resize

    Hello,
    Is there a way to resize the sequence name in the Sequence File Hierarchy Call Graph? I have a need to make the sequence names long and it does not fit in the file hierarchy.
    Thanks.

    There is not a way.  The objects that hold the sequence names are a default size.  The best way to be able to view the whole name is just to scroll over top of the object.
    Jesse S.
    Applications Engineer
    National Instruments

Maybe you are looking for

  • New Page Format in Smartforms

    Hi All, I am working on smartforms. I have created a new page format of width 25 cm and width 30cm according to client's requirement. Smartform is  for customer invoice which is a pre-printed and i have to get data into that. In sform i have given th

  • Recording audio with the macbook

    HOWDY HO EVERBODY!!! is there anybody out there who is using their macbook to record audio?i'd really like to know the results/problems.for those of you out there who do use computer based audio recording software,and r using pro tools in particular,

  • Grants-Projects/Awards Reconciliation & GL

    What are the main reasons for reconciliation problems between Projects and Awards, including summary and detailed information?? Grants and GL reconciliation-main problems? The project and award segments in GL are necessary? If not, how to reconciliat

  • Request for sample ZXRSRU01 code-  pass to VKF

    Hello, I wrote an earlier mssg but I fear I may have been too complicated in my request. I would like to pull a BEx variable user entry in and use it to calculate a key figure. I have the virtual KF code working fine. I just need help pulling the use

  • Certain Sounds not working

    Just recently my iphone stopped making sounds for when my mail was sent or received, or when I had a voicemail or any of my calendar alerts. I have checked my settings and tried switching them off and then on again but nothing seems to work. Even whe