Andrew Thompson wrote:
Quote:
Robert Larsen wrote:
.. Quote:
>I have some code that saves an image to a file using ImageIO. And it
>works for all formats except jpeg. A scaled down version follows:
| >
AN SSCCE is generally more useful than a 'scaled
down' version.
|
Done:
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.*;
import javax.swing.*;
import java.awt.*;
public class SSCCE extends JFrame {
private final static int WIDTH = 400;
private final static int HEIGHT = 400;
private BufferedImage image;
public SSCCE() {
super("Bad JPEG");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ImagePanel p = new ImagePanel(WIDTH, HEIGHT);
pack();
setSize(WIDTH + getInsets().left + getInsets().right, HEIGHT +
getInsets().top + getInsets().bottom);
getContentPane().add(p);
setVisible(true);
}
public void write(String filename) throws IOException {
int idx = filename.lastIndexOf('.');
if (idx >= 0) {
File file = new File(filename);
String format = filename.substring(idx + 1).toLowerCase();
ImageIO.write(image, format, file);
}
}
private class ImagePanel extends JPanel {
public ImagePanel(Dimension d) {
this(d.width, d.height);
}
public ImagePanel(int w, int h) {
setSize(w, h);
image = new BufferedImage(w 0 ? w : 1, h 0 ? h : 1,
BufferedImage.TYPE_INT_ARGB);
GradientPaint gp = new GradientPaint(0, 0, Color.blue, w, h,
Color.green);
Graphics2D g2d = image.createGraphics();
g2d.setPaint(gp);
g2d.fillRect(0, 0, w, h);
gp = new GradientPaint(0, 0, Color.green, w, h, Color.blue);
g2d.setPaint(gp);
g2d.fillArc(0, 0, w, h, 0, 360);
}
public void paintComponent(Graphics g) {
g.drawImage(image, 0, 0, this);
}
}
public static void main(String args[]) throws IOException {
SSCCE sscce = new SSCCE();
for (String filename : args) {
System.out.println("Saving to " + filename);
sscce.write(filename);
}
}
}
Usage:
robert-desktop:~/code/ToolboxNG $ javac SSCCE.java
robert-desktop:~/code/ToolboxNG $ java SSCCE test.png test.gif test.jpg
test.bmp
Saving to test.png
Saving to test.gif
Saving to test.jpg
Saving to test.bmp
robert-desktop:~/code/ToolboxNG $
This should pop up a window displaying the image as it should look.
The PNG and GIF look correct, but the JPG looks wrong (it CAN be
displayed using an image editor but Firefox and probably IE won't have
anything to do with it). The BMP file has a zero length.