Problem mit imageIO und ImageIcon

sven-ber

Grünschnabel
Hallo zusammen,

ich habe ein Tool geschrieben, welches ein ImageIcon auf Festplatte speichern soll.
Das funktioniert soweit ganz gut. Das ist der Code dazu:

Code:
public void saveImage(File url)
	{
		BufferedImage bi = new BufferedImage(this.finishedPicture.getIconWidth(),this.finishedPicture.getIconHeight(),
				Transparency.TRANSLUCENT);
		Graphics2D bg = bi.createGraphics();
		bg.drawImage(this.finishedPicture.getImage(), 0, 0, this.finishedPicture.getIconWidth(), 
				this.finishedPicture.getIconHeight(), 0, 0, this.finishedPicture.getIconWidth(),
				this.finishedPicture.getIconHeight(), null);
		try {
			ImageIO.write(bi, "jpg", url);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

Die Variable finishedPicture ist ein ImageIcon.

Das Problem ist folgendes: Aus irgendeinem Grund wird das Bild beim speichern verfälscht.
Die Farben stimmen mit dem Orignalbild nicht mehr über ein. Woran kann das liegen?
 
Ich habe den Fehler gefunden. Die write Methode von imageIO benötigt ein RenderedImage und kein Image.

Nun weis ich aber nicht wie ich aus einem Image ein rendereImage generiere. Könnt ihr mir bitte weiterhelfen?
 
Hi,

soweit ich gesehen habe, ist ein BufferedImage auch ein Rendered Image. Ein normales Image kann man mit folgendem Code in ein BufferedImage umwandeln:

Code:
    /**
     * Converts the given image into a {@link BufferedImage} with the given
     * image type. The image type is on the of the <code>BufferedImage</code>'s
     * constants like {@link BufferedImage#TYPE_INT_RGB}.
     * @param image Image to convert into a <code>BufferedImage</code>
     * @param imageType Image type of the new image.
     * @return New <code>BufferedImage</code> containing the contents of
     *      <code>image</code>.
     */
    public static BufferedImage toBufferedImage(Image image, int imageType)
    {
        // This code ensures that all the pixels in the image are loaded
        image = new ImageIcon(image).getImage();

        // Create a buffered image using the default color model
        BufferedImage bimage = new BufferedImage(image.getWidth(null), image.
                getHeight(null), imageType);

        // Copy image to buffered image
        Graphics g = bimage.createGraphics();

        // Paint the image onto the buffered image
        g.drawImage(image, 0, 0, null);
        g.dispose();

        return bimage;
    }

Grüße
Andi
 
Zurück