ImageIO.write()方法和png

时间:2011-02-23 12:26:15

标签: java image-processing

为什么ImageIO.write(bufferedimage_dest,"png",new File(filedest));写jpg(没有透明色)文件而不是png?

加了:

static BufferedImage createResizedCopy(Image originalImage, 
                int scaledWidth, int scaledHeight, 
                boolean preserveAlpha)
    {
        System.out.println("resizing...");
        int imageType = preserveAlpha ? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB;
        BufferedImage scaledBI = new BufferedImage(scaledWidth, scaledHeight, imageType);
        Graphics2D g = scaledBI.createGraphics();
        if (preserveAlpha) {
                g.setComposite(AlphaComposite.Src);
        }
        g.drawImage(originalImage, 0, 0, scaledWidth, scaledHeight, null); 
        g.dispose();
        return scaledBI;
    }


  public static void scale(String src, int width, int height, String dest)
     throws IOException {
   BufferedImage bsrc = ImageIO.read(new File(src));
   BufferedImage bdest =
      new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
   bdest = createResizedCopy(bsrc, width, height, false);
   ImageIO.write(bdest,"png",new File(dest));
  }

加了:

好吧,在我调用的main()函数中

ScaleJPG.scale((args[0],Integer.parseInt(args[1]),Integer.parseInt(args[2]), args[3]););

而不是

ScalePNG.scale((args[0],Integer.parseInt(args[1]),Integer.parseInt(args[2]), args[3]););

ScaleJPG与此文件夹中的上一课类似。

我必须丢弃记事本并仅使用IDE。 要删除的问题。

3 个答案:

答案 0 :(得分:2)

您需要缓冲的图片才能使图片类型为BufferedImage.TYPE_INT_ARGB

答案 1 :(得分:1)

添加

g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);

之前g.drawImage(originalImage, 0, 0, scaledWidth, scaledHeight, null);createResizedCopy函数。

答案 2 :(得分:0)

没有。这个简单的测试类验证它:

import java.awt.image.*;
import java.io.File;
import javax.imageio.*;

public class Main
{
    public static void main (String [] args) throws Exception
    {
        BufferedImage bi = new BufferedImage(100,100,BufferedImage.TYPE_INT_ARGB);
        ImageIO.write(bi, "png", new File("test.png"));
    }
} 

编译并执行它会像预期的那样生成.png文件:

$ javac Main.java
$ java Main
$ file test.png 
test.png: PNG image, 100 x 100, 8-bit/color RGBA, non-interlaced
$