首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在压缩照片时设置背景透明

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

Stack Overflow用户
提问于 2014-04-03 08:33:30
回答 1查看 408关注 0票数 0

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

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

这是我的代码:

代码语言:javascript
复制
        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();
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-04-11 03:24:41

代码语言:javascript
复制
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);
    }
}
}

它起作用了。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22832054

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档