• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 218
  • Last Modified:

Saving an array to JPG or GIF file format

I have a program where I have to locate a sub-image within a larger image.  I open the image files and convert them to 3D arrays, manipulate the images.  I have figured out how to save to bmp, but really need to save the image to jpg format.  I can supply the image in either a 3D array [col][row][32 bit color] or 2D array [index][32 bit color] or 1D array of 32 bit colors.  How do I save any of these to a jpg file format, whatever is easier.  This may seem trivial but I am not a JAVA programmer, please help!
0
ssche2bu
Asked:
ssche2bu
1 Solution
 
CEHJCommented:
This contains the code you'd need for that:

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import java.awt.*;
import java.awt.image.*;
import java.awt.geom.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;

public class Shape2Jpeg {

  public static void main(String[] args){
    JFrame f = new JFrame();
    f.getContentPane().add(new ShapePanel());
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setSize(300, 200);
    f.setVisible(true);
  }

}

class ShapePanel extends JPanel implements MouseListener {
  boolean highlighted;
  Shape shape;
  Paint normalPaint;
  BufferedImage imageJpeg;
  Graphics2D g2dJpeg;

  public ShapePanel() {
    super();
    shape = new Rectangle2D.Float(0.f, 0.f, 100.f, 50.f);
    // Create image to save as Jpeg
    imageJpeg = new BufferedImage(shape.getBounds().width, shape.getBounds().height, BufferedImage.TYPE_INT_RGB);
    g2dJpeg = imageJpeg.createGraphics();
    normalPaint = Color.red;
    addMouseListener(this);
  }

  public void paintComponent(Graphics _g) {
    Graphics2D g = (Graphics2D)_g;
    g.setPaint(normalPaint);
    g.fill(shape);
    g.draw(shape);
  }

  public void mouseClicked(MouseEvent e) {
    // Save shape as Jpeg
    try {
      g2dJpeg.setPaint(normalPaint);
      g2dJpeg.fill(shape);
      // draw the shape to the Jpeg image
      g2dJpeg.draw(shape);
      FileOutputStream in = new FileOutputStream("shape.jpg");
      JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(in);
      encoder.encode(imageJpeg);
      in.close();
    }
    catch (IOException ex) {
      ex.printStackTrace();
    }



  }

  public void mouseEntered(MouseEvent e) {}
  public void mouseExited(MouseEvent e) {}
  public void mousePressed(MouseEvent e) {}
  public void mouseReleased(MouseEvent e) {}

}
0

Featured Post

Independent Software Vendors: 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!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now