• Advertisement
Sign in to follow this  

[java] How do you create a jpg image from Graphics?

This topic is 4927 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I found a solution on the net saying something like. import java.io.ByteArrayOutputStream; import java.awt.Frame; import java.awt.Graphics; import java.awt.image.BufferedImage; BufferedImage awtImage = new BufferedImage(this.getWidth(),this.getHeight(),BufferedImage.TYPE_INT_RGB); Graphics g = awtImage.getGraphics(); this.printAll(g); try { ByteArrayOutputStream out = new ByteArrayOutputStream(); JPEGImageEncoderImpl j = new JPEGImageEncoderImpl(out); j.encode(awtImage); out.close(); } catch (Exception e) { e.printStackTrace(); } but I still cannot understand how I create that jpg file and put my encoded stuff in it.

Share this post


Link to post
Share on other sites
Advertisement
You've got the ByteArrayOutputStream. It writes stuff to a byte array. The byte array contains the encoded jpeg data.

Use ByteArrayOutputStream.toByteArray() to get the byte array. Then you just create a file and write the byte array to it.

Share this post


Link to post
Share on other sites
I tried this code...

fw = new FileWriter(StrategicWarfare.getDataPath() + "ExtraMap", false);
bw = new BufferedWriter(fw);
outFile = new PrintWriter(bw);

byte[] tmp=out.toByteArray();
for(int i=0;i<tmp.length;i++)
outFile.write(tmp);


The file was 600 kilobyte and not a jpg. I could not open that file with any paint program even after renaming it to ExtraMap.jpg

Share this post


Link to post
Share on other sites
Quote:
Original post by tombr
Use a FileOutputStream instead of the Writer.


I tried it. The jpg file was created but still I could not open it.

"JPEG marker segment is too short (the file may be truncated or incomplete)

Share this post


Link to post
Share on other sites
I do not know what is wrong with your code. There is apparently another way to save jpegs, using the class javax.imageio.ImageIO.

ImageIO.write(someBufferedImage,"jpeg",someFile);

It might work better.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement