压缩照片时如何设置背景透明

时间:2014-04-03 08:33:31

标签: java awt transparency bufferedimage graphics2d

我正在压缩照片,但是一个问题阻止了我。 它调用Graphics2D的drawImage,但最终输出显示源照片的透明区域被复制为黑色背景到最终照片。

为什么?当源照片的区域具有透明背景时如何设置背景透明?

这是我的代码:

        Image image = ImageIO.read(new File(path + fileName));
        int imageWidth = image.getWidth(null);
        int imageHeight = image.getHeight(null);
        float scale = getRatio(imageWidth, imageHeight, 274, 392);
        imageWidth = (int) (scale * imageWidth);
        imageHeight = (int) (scale * imageHeight);

        image = image.getScaledInstance(imageWidth, imageHeight,
                Image.SCALE_SMOOTH);
        BufferedImage mBufferedImage = new BufferedImage(imageWidth,
                imageHeight, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = mBufferedImage.createGraphics();

        g2.drawImage(image, 0, 0, imageWidth, imageHeight, null);
        g2.dispose();

        FileOutputStream out = new FileOutputStream(path + toFileName);
        ImageIO.write(mBufferedImage, "png", out);
        out.close();

1 个答案:

答案 0 :(得分:0)

package com.hb.util;


import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.awt.image.FilteredImageSource;
import java.awt.image.ImageFilter;
import java.awt.image.ImageProducer;
import java.awt.image.RGBImageFilter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import org.apache.commons.io.FileUtils;
import org.fusesource.hawtbuf.ByteArrayInputStream;

public class ImageCompressingUtils {

public static void main(String[] args) {
    String path = "F:/2huazhuangpin990x395.jpg";
    long c = System.currentTimeMillis();
    ImageCompressingUtils.compress(path, "F:/1.png", "png", 0.8);
    System.out.println("elapse time:"
            + (System.currentTimeMillis() - c) / 1000.0f + "s");
}

public static BufferedImage getTransparentScaledImage(BufferedImage originalImage, int finalWidth, int finalHeight) {
    int originalWidth = originalImage.getWidth();
    int originalHeight = originalImage.getHeight();

    if (originalWidth == 0 || originalHeight == 0
            || (originalWidth == finalWidth && originalHeight == finalHeight)) {
        return originalImage;
    }

    BufferedImage intermediateImage = new BufferedImage(finalWidth, finalHeight, BufferedImage.TYPE_INT_ARGB);
    Graphics2D gi = intermediateImage.createGraphics();
    gi.setComposite(AlphaComposite.SrcOver);
    gi.setColor(new Color(0, 0, 0, 0));
    gi.fillRect(0, 0, finalWidth, finalHeight);
    gi.drawImage(originalImage.getScaledInstance(finalWidth, finalHeight, Image.SCALE_SMOOTH), 0, 0, null);
    gi.dispose();

    return intermediateImage;
}

public static Image makeColorTransparent(Image im, final Color color) {
    ImageFilter filter = new RGBImageFilter() {
        public int markerRGB = color.getRGB() | 0xFF000000;

        public final int filterRGB(int x, int y, int rgb) {
            if ((rgb | 0xFF000000) == markerRGB) {
                return 0x00FFFFFF & rgb;
            } else {
                return rgb;
            }
        }
    };

    ImageProducer ip = new FilteredImageSource(im.getSource(), filter);
    return Toolkit.getDefaultToolkit().createImage(ip);
}

/**
 * 压缩
 * @param datas 数据
 * @param rate 压缩比率
 * @return
 */
public static byte[] compress(byte[] datas, String format, double rate) {
    try {
        BufferedImage srcImage = ImageIO.read(new ByteArrayInputStream(datas));
        int width = srcImage.getWidth();
        int height = srcImage.getHeight();
        BufferedImage descImage = getTransparentScaledImage(srcImage, ((Double)(width * rate)).intValue(), ((Double) (height * rate)).intValue());
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ImageIO.write(descImage, format == null ? "jpg" : format, out);
        return out.toByteArray();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

public static void compress(String srcPath, String descPath, String format, double rate) {
    try {
        byte[] datas = FileUtils.readFileToByteArray(new File(srcPath));
        byte[] finalDatas = compress(datas, format, rate);
        FileUtils.writeByteArrayToFile(new File(descPath), finalDatas);
    } catch(IOException e) {
        throw new RuntimeException(e);
    }
}
}

它有效。