?
Solved

Image as an Object

Posted on 2003-03-16
44
Medium Priority
?
234 Views
Last Modified: 2013-11-23
Now I have everything working, but I can't find anything on how to save a image as an object.  Is this possible, if so how do I do this?

I know how to save text as objects, but how do I save an image as an object of a file?

0
Comment
Question by:gujuraja143
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 20
  • 20
  • 3
  • +1
44 Comments
 
LVL 3

Expert Comment

by:allahabad
ID: 8148371
  try {
       

         FileOutputStream ostream = new FileOutputStream("imagestoarge.tmp");
         ObjectOutputStream p = new ObjectOutputStream(ostream);

         p.writeObject(imageObject);
       
         p.flush();
         ostream.close();
      }
      catch(Exception e){
         e.getMessage();
      }
0
 
LVL 92

Expert Comment

by:objects
ID: 8148415
> Is this possible, if so how do I do this?

You cannot save the image object itself.
You can however encode the image using an image format such as jpg, or gif.
0
 

Author Comment

by:gujuraja143
ID: 8148438
What do you mean?  I can't save the image as an object?
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 92

Expert Comment

by:objects
ID: 8148503
What exactly is it you are trying to do?
0
 

Author Comment

by:gujuraja143
ID: 8148620
Im trying to save some information about the image and also some other information that I am trying to get from the user.  This information is stored as objects in a file.

The information I can save, but I was wondering if it is possible to save that image also as an object in that file.  So when I need it later, I will be able to open that specific file and it will have the image there and its information.

Thanks
0
 
LVL 92

Expert Comment

by:objects
ID: 8148695
No you can't save your image as an object.
you need to encode the image data as I mentioned above.
0
 
LVL 92

Expert Comment

by:objects
ID: 8148782
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode((BufferedImage)image);


0
 

Author Comment

by:gujuraja143
ID: 8149025
My last question is, after I encode the image into that file, I can still store objects in that file, right?

Will I need to put something in that file to tell what the objects are and what the image is, like a separator?

Thank you again.
0
 
LVL 92

Expert Comment

by:objects
ID: 8149159
You should be ok, but can't say for certain without trying it.
0
 

Author Comment

by:gujuraja143
ID: 8149242
Couldn't you have the image as attribute in the object, like lets say if I am saving different attributes, and one of those attributes is Image, would this be possible?

Like if we wanted to open the object up, the specific attributes will be there.  Will this work? or no?

I am just thinking of different ideas of how to go about doing this.

Thank you again,

I am increasing the points for your troubles
0
 
LVL 92

Expert Comment

by:objects
ID: 8149263
> Couldn't you have the image as attribute in the object

Thats no different than saving the image object directly.
You cannout do it because the Image object is not Serializable.
0
 
LVL 92

Expert Comment

by:objects
ID: 8149291
If you wanted to include the image as an attribute of another object then you could encode the image to a byte array and store that byte arrat as an object attribute.
0
 

Author Comment

by:gujuraja143
ID: 8149432
Byte arrary...How would I change the image to a byte array and then the byte array to the image back again.  

If this works, this would be perfect.

Thank you,

If I get this working, I will increase the points to 500,

Thank you in advance.
0
 
LVL 92

Expert Comment

by:objects
ID: 8149477
Here you go for JPEG encoding:

ByteArrayOutputStream out = new ByteArrayOutputStream();
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode((BufferedImage)image);
out.close();
byte[] data = out.toByteArray();


0
 
LVL 86

Expert Comment

by:CEHJ
ID: 8154296
This is one way of doing this. It looks quite a lot of code, but this is mostly in main, which you can delete once you see how it works. This shows an image, serializes it, along with some properties and then deserializes it and shows it in another window:

import java.io.*;
import java.awt.*;
import java.awt.image.*;
import java.util.Hashtable;

public class ImageWrapper implements Serializable {
  private int[] imageData;
  private Hashtable properties;
  transient private Image image;
  private int imageWidth;
  private int imageHeight;


  public ImageWrapper(Image image) {
    properties = new Hashtable();
    this.image = image;
  }

  public static void main(String[] args) {

    try {
      // Create a test image dynamically
      int width= 200;
      int height = 200;
      final BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
      WritableRaster raster = image.getRaster();
      // Make an image of light blue colour
      int[] colour = { 0xcc, 0xcc, 0xff };
      for(int i = 0;i < width;i++) {
        for(int j = 0;j < height;j++) {
          raster.setPixel(i, j, colour);
        }
      }

      // Show image in frame

      javax.swing.JFrame f = new javax.swing.JFrame();

      f.setContentPane(new javax.swing.JPanel() {

        public void paintComponent(java.awt.Graphics g) {
          g.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null);
        }
      });
      f.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
      f.setSize(300, 300);
      f.setVisible(true);


      // Make an ImageWrapper
      ImageWrapper iw = new ImageWrapper(image);
      // Write a to the;
      iw.setImageWidth(width);
      iw.setImageHeight(height);
      iw.putProperty("Title", "Light blue rectangle image");
      iw.saveImageData();


      // Serialize wrapper data

      // Create temp file
      File temp = File.createTempFile("image", "dat");
      temp.deleteOnExit();
      ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(temp));
      System.out.println("Serializing image data");
      out.writeObject(iw);
      out.close();

      // Deserialize wrapper data

      ObjectInputStream in = new ObjectInputStream(new FileInputStream(temp));
      System.out.println("Deserializing image data");
      ImageWrapper savedImage = (ImageWrapper)in.readObject();
      System.out.println("Reading image wrapper data...");
      System.out.println("Title = " + (String)savedImage.getProperty("Title"));

      // Now recreate image
      int w = savedImage.getImageWidth();
      int h = savedImage.getImageHeight();
      final BufferedImage recreatedImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
      WritableRaster wr = recreatedImage.getRaster();
      wr.setSamples(0, 0, w, h, 0, savedImage.getImageData());


      // Show RECREATED image in frame

      javax.swing.JFrame fNew = new javax.swing.JFrame();

      fNew.setContentPane(new javax.swing.JPanel() {

        public void paintComponent(java.awt.Graphics g) {
          g.drawImage(image, 0, 0, recreatedImage.getWidth(), recreatedImage.getHeight(), null);
        }
      });
      fNew.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
      fNew.setSize(300, 300);
      fNew.setLocation(400, 0);
      fNew.setVisible(true);
    }
    catch(Exception e) {
      e.printStackTrace();
    }

  }

  public void saveImageData() {
    // Create a buffer to hold image data
    int width = image.getWidth(null);
    int height = image.getHeight(null);
    int[] buff = new int[width * height];
    PixelGrabber pg = new PixelGrabber(image, 0, 0, width, height, buff, 0, 1);
    Object data = pg.getPixels();
    //DEBUG
    System.out.println(data);

    // clone the int array
    int[] tmp = (int[])data;
    int sz = tmp.length;
    imageData = new int[sz];
    System.arraycopy(tmp, 0, imageData, 0, sz);

  }

  public void putProperty(Object key, Object value) {
    properties.put(key, value);
  }

  public Object getProperty(Object key) {
    return properties.get(key);
  }

  public int[] getImageData(){
    return this.imageData;
  }


  public void setImageWidth(int imageWidth){
    this.imageWidth = imageWidth;
  }

  public int getImageWidth(){
    return this.imageWidth;
  }


  public void setImageHeight(int imageHeight){
    this.imageHeight = imageHeight;
  }

  public int getImageHeight(){
    return this.imageHeight;
  }


}
0
 
LVL 92

Expert Comment

by:objects
ID: 8155052
Not sure on the accuracy of saving just the pixel data would be as you lose colour model details etc, and it also required 4 bytes per pixel which is quite expensive.

Better to use an appropriate image encoder that meets your needs imo.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 8155426
I'm not sure about the following:

>>encoder.encode((BufferedImage)image);

(the source may not be a BufferedImage)


and also symmetricality: the source data may not be recoverable after encode/decode

0
 
LVL 92

Expert Comment

by:objects
ID: 8155472
> (the source may not be a BufferedImage)

1. easy to make it one
2. that was simply an encoder example.

> the source data may not be recoverable after encode/decode

Depends on the encoder used. I only supplied jpeg as an example, png or gif could similiarily be used.
0
 
LVL 92

Expert Comment

by:objects
ID: 8155500
Here are a stack of good resources on saving images:
http://www.geocities.com/marcoschmidt.geo/java-image-coding.html
0
 

Author Comment

by:gujuraja143
ID: 8279693
CEHJ, that code somewhat works, but the second time you open the image, shouldnt that be recreatedImage instead of image.

when i did replace that with recreatedImage, it doesn't show the image, it just showes black, everything black.

0
 
LVL 86

Expert Comment

by:CEHJ
ID: 8285431
>>shouldnt that be recreatedImage instead of image.

Yes - you're right.

>>it just showes black, everything black.

Oh dear - i'll try and have a look at it again later
0
 

Author Comment

by:gujuraja143
ID: 8340482
If anyone can help me on this, I am raising the point value to a 1000.

I have tried getting this working, but I can't manage to do this.
0
 

Author Comment

by:gujuraja143
ID: 8340483
I will give the person that gets this answer the 500 other points.
0
 
LVL 92

Expert Comment

by:objects
ID: 8344933
Did you try the code I posted?
What have you tried?
0
 

Author Comment

by:gujuraja143
ID: 8344950
for your code, how would I store that that byte array after I try what you gave me?....I tried doing it but couldnt really figure it out.

also after I do store it as a byte array, how would I recompile the image back again?

thanks.
0
 
LVL 92

Accepted Solution

by:
objects earned 2000 total points
ID: 8345009
Example 1: Encoding an image in a byte array and saving that byte array to a file:
=======================================================

ByteArrayOutputStream out = new ByteArrayOutputStream();
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode((BufferedImage)image);
out.close();
byte[] data = out.toByteArray();

// To save bytes to a file

FileOutputStream fout = new FileOutputStream("my.jpg");
fout.write(data);
fout.close();

// To load image from byte array

Image im = Toolkit.getDefaultToolkit().createImage(data);

Example 2: Encoding image directly to a file
============================================

FileOutputStream out = new FileOutputStream("my.jpg");
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode((BufferedImage)image);
out.close();

// To save image directly to file

FileOutputStream out = new FileOutputStream("my.jpg");
0
 

Author Comment

by:gujuraja143
ID: 8384503
// loading image then saving it

                  fileName = fileChooser.getSelectedFile().getAbsolutePath();
                   Toolkit toolkit = Toolkit.getDefaultToolkit();
                    image = toolkit.getImage(fileName);
                   
                    MediaTracker mediaTracker = new MediaTracker(new Frame());
                   mediaTracker.addImage(image, 0);
                   mediaTracker.waitForID(0);
                   
                   ByteArrayOutputStream out = new ByteArrayOutputStream();
                    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
                    encoder.encode((BufferedImage)image);
                    out.close();
                    byte[] data = out.toByteArray();
                   
                    FileOutputStream fout = new FileOutputStream(fileName+".xpg");
                    fout.write(data);



for some weird reason this is giving me an error any clue?


and also after i save this file, and i open a type xpg file, how would I tell java that this file contains a byte array?  or does this line..

Image im = Toolkit.getDefaultToolkit().createImage(data);

do it automatically.  Like lets say I go to my application and say open type .xpg file, and then I open it, would that like automatically do that?

Thanks
0
 

Author Comment

by:gujuraja143
ID: 8384530
// loading image then saving it

                  fileName = fileChooser.getSelectedFile().getAbsolutePath();
                   Toolkit toolkit = Toolkit.getDefaultToolkit();
                    image = toolkit.getImage(fileName);
                   
                    MediaTracker mediaTracker = new MediaTracker(new Frame());
                   mediaTracker.addImage(image, 0);
                   mediaTracker.waitForID(0);
                   
                   ByteArrayOutputStream out = new ByteArrayOutputStream();
                    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
                    encoder.encode((BufferedImage)image);
                    out.close();
                    byte[] data = out.toByteArray();
                   
                    FileOutputStream fout = new FileOutputStream(fileName+".xpg");
                    fout.write(data);



for some weird reason this is giving me an error any clue?


and also after i save this file, and i open a type xpg file, how would I tell java that this file contains a byte array?  or does this line..

Image im = Toolkit.getDefaultToolkit().createImage(data);

do it automatically.  Like lets say I go to my application and say open type .xpg file, and then I open it, would that like automatically do that?

Thanks
0
 

Author Comment

by:gujuraja143
ID: 8384556
// loading image then saving it

                  fileName = fileChooser.getSelectedFile().getAbsolutePath();
                   Toolkit toolkit = Toolkit.getDefaultToolkit();
                    image = toolkit.getImage(fileName);
                   
                    MediaTracker mediaTracker = new MediaTracker(new Frame());
                   mediaTracker.addImage(image, 0);
                   mediaTracker.waitForID(0);
                   
                   ByteArrayOutputStream out = new ByteArrayOutputStream();
                    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
                    encoder.encode((BufferedImage)image);
                    out.close();
                    byte[] data = out.toByteArray();
                   
                    FileOutputStream fout = new FileOutputStream(fileName+".xpg");
                    fout.write(data);



for some weird reason this is giving me an error any clue?


and also after i save this file, and i open a type xpg file, how would I tell java that this file contains a byte array?  or does this line..

Image im = Toolkit.getDefaultToolkit().createImage(data);

do it automatically.  Like lets say I go to my application and say open type .xpg file, and then I open it, would that like automatically do that?

Thanks
0
 
LVL 92

Expert Comment

by:objects
ID: 8384593
> this is giving me an error any clue?

Whats the error?

> how would I tell java that this file contains a byte array?  

All files are basically an array of bytes.


0
 

Author Comment

by:gujuraja143
ID: 8384633
// loading image then saving it

                  fileName = fileChooser.getSelectedFile().getAbsolutePath();
                   Toolkit toolkit = Toolkit.getDefaultToolkit();
                    image = toolkit.getImage(fileName);
                   
                    MediaTracker mediaTracker = new MediaTracker(new Frame());
                   mediaTracker.addImage(image, 0);
                   mediaTracker.waitForID(0);
                   
                   ByteArrayOutputStream out = new ByteArrayOutputStream();
                    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
                    encoder.encode((BufferedImage)image);
                    out.close();
                    byte[] data = out.toByteArray();
                   
                    FileOutputStream fout = new FileOutputStream(fileName+".xpg");
                    fout.write(data);



for some weird reason this is giving me an error any clue?


and also after i save this file, and i open a type xpg file, how would I tell java that this file contains a byte array?  or does this line..

Image im = Toolkit.getDefaultToolkit().createImage(data);

do it automatically.  Like lets say I go to my application and say open type .xpg file, and then I open it, would that like automatically do that?

Thanks
0
 

Author Comment

by:gujuraja143
ID: 8384652
well its not giving the error when i compile the code, it gives me an error when i run the code,

java.lang.ClassCastException
    at Trans.imageChooser(Trans.java:660)

this is basically this line:

encoder.encode((BufferedImage)image);

that line is #660.

Thanks
0
 
LVL 92

Expert Comment

by:objects
ID: 8384694
That would be because you image is not a BufferedImage.

Here's a JPEG encoder that does not require a BufferedImage.
0
 

Author Comment

by:gujuraja143
ID: 8384766
What do you mean?  So what JPEG encoder should I use, or how should I write that?

0
 
LVL 92

Expert Comment

by:objects
ID: 8384848
woops forgot to paste the link :)

http://www.afu.com/jpeg.txt

Which you use is up to you, you can use this one directly with your image, or create a BufferedImage and use Sun's.


0
 

Author Comment

by:gujuraja143
ID: 8385054

                    final Image im = Toolkit.getDefaultToolkit().createImage(data);
final BufferedImage recreatedImage = new BufferedImage(500, 500, BufferedImage.TYPE_INT_RGB);
javax.swing.JFrame fNew = new javax.swing.JFrame();

                    fNew.setContentPane(new javax.swing.JPanel() {

                           public void paintComponent(java.awt.Graphics g) {
                             g.drawImage(recreatedImage, 0, 0, im.getWidth(null), im.getHeight(null), null);
                           }
                    });
                         fNew.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
                    fNew.setSize(300, 300);
                    fNew.setLocation(400, 0);
                    fNew.setVisible(true);


OK last question,

I believe it stores the information in a byte array, but I dont know if this is right?  When I open the image, it opens but its all black???  So is there something wrong in my code opening the image?
0
 

Author Comment

by:gujuraja143
ID: 8385091
              ByteArrayOutputStream out = new ByteArrayOutputStream();
                    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
                    final BufferedImage newimage = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_RGB);
                    encoder.encode((BufferedImage)newimage);
                    out.close();
                    byte[] data = out.toByteArray();

Thats how I make the bufferedImage and store it also...
0
 
LVL 92

Expert Comment

by:objects
ID: 8385136
You do not appear to be painting your image to your newly created image.

Graphics@d g2d = newimage.createGraphics();
g2d.drawImage(image, 0, 0, null);
0
 

Author Comment

by:gujuraja143
ID: 8385212
for some weird reason my compiler cant find Graphics2d?

its saying that it cannot resolve symbol.

I also tried transporting other librarys such as Graphics, and also the Graphics2d library itself??

any reason for this?

wow this is taking a long time.....

thanks for your help, you are probably getting fustrated, but I will make it worth while after I get this working.

Thanks
0
 
LVL 92

Expert Comment

by:objects
ID: 8385226
Justr try:

Graphics g = newimage.createGraphics();
g.drawImage(image, 0, 0, null);
0
 

Author Comment

by:gujuraja143
ID: 8385350
                  fileName = fileChooser.getSelectedFile().getAbsolutePath();
                   Toolkit toolkit = Toolkit.getDefaultToolkit();
                    image = toolkit.getImage(fileName);
                   
                    MediaTracker mediaTracker = new MediaTracker(new Frame());
                   mediaTracker.addImage(image, 0);
                   mediaTracker.waitForID(0);
                   
                   ByteArrayOutputStream out = new ByteArrayOutputStream();
                    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
                    final BufferedImage newimage = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_RGB);
                    Graphics g = newimage.createGraphics();
                    g.drawImage(image, 0, 0, null);
                    encoder.encode((BufferedImage)newimage);
                    out.close();
                    byte[] data = out.toByteArray();
                   FileOutputStream fout = new FileOutputStream(fileName+".xpg");
                   fout.write(data);
                    fout.close();
                  final Image im = Toolkit.getDefaultToolkit().createImage(data);
                   final BufferedImage recreatedImage = new BufferedImage(500, 500, BufferedImage.TYPE_INT_RGB);
                   javax.swing.JFrame fNew = new javax.swing.JFrame();

                    fNew.setContentPane(new javax.swing.JPanel() {

                           public void paintComponent(java.awt.Graphics g) {
                             g.drawImage(recreatedImage, 0, 0, im.getWidth(null), im.getHeight(null), null);
                           }
                    });
                         fNew.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
                    fNew.setSize(300, 300);
                    fNew.setLocation(400, 0);
                    fNew.setVisible(true);




thats all my code for viewing and saving the image...but it's still not working, its still showing all black.

Thanks
0
 
LVL 92

Expert Comment

by:objects
ID: 8385372
Yes, recreatedImage is blank.
Why aren't you just painting 'im'?
0
 

Author Comment

by:gujuraja143
ID: 8385424
ok that works, it stores it in the file.

now last question, right now im opening the image directly right after i create the byte array data.

how would I do it when I choose the file, like right here...im telling the program where exactly the file is located:

File test = new File("C:/test.jpg.xpg");

how would I open that file?

and the points for you will be waiting, im creating the points right now.

Thanks
0
 
LVL 92

Expert Comment

by:objects
ID: 8385491
image = toolkit.getImage(test.getPath());

or

image = toolkit.getImage("C:/test.jpg.xpg");

0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
In this post we will learn how to make Android Gesture Tutorial and give different functionality whenever a user Touch or Scroll android screen.
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
This video teaches viewers about errors in exception handling.
Suggested Courses
Course of the Month11 days, 20 hours left to enroll

752 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question