Note that there are some explanatory texts on larger screens.

plurals
  1. POResizing BufferedImages and storing them to file results in black background for JPG images
    primarykey
    data
    text
    <p>I have the following code:</p> <pre><code>import java.awt.Graphics2D; import java.awt.Image; import java.awt.image.BufferedImage; import java.io.File; import javax.imageio.ImageIO; public class JavaApplication { public static void main(String[] args) throws Exception { File orig = new File ("/home/xxx/Pictures/xxx.jpg"); BufferedImage bm1 = ImageIO.read(orig); Image scaled = bm1.getScaledInstance(100, 200, BufferedImage.SCALE_SMOOTH); BufferedImage bm2 = toBufferedImage(scaled); File resized = new File ("/home/xxx/Pictures/resized.jpg"); ImageIO.write(bm2, "jpg", resized); } public static BufferedImage toBufferedImage(Image img) { if (img instanceof BufferedImage) { return (BufferedImage) img; } BufferedImage bimage = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB); bimage.getGraphics().drawImage(img, 0, 0 , null); return bimage; } } </code></pre> <p>If I use this code on a .png file, it works fine, and resizes the file as expected. However on jpg files, it results in a black background.</p> <p>If I remove the <code>getScaledInstance()</code> code and simply try to re-write the original <code>bm1</code> to the disk using <code>ImageIO.write(bm1, "jpg", resized)</code>, that works fine. Only when resizing using <code>getScaledInstance()</code> and then trying to conver the resulting <code>Image</code> back to <code>BufferedImage</code>, do I get a completely black background file.</p> <p>Any ideas on how to fix this, or what I'm doing wrong?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload