我想加载没有额外白色像素的图像。我该怎么做呢? [英] I want to load an image without the extra white pixels. How do I do this?

查看:127
本文介绍了我想加载没有额外白色像素的图像。我该怎么做呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在画布上绘制图像时,图像周围的白色像素也存在于图像边界。关于如何防止这种情况的任何提示?

When i draw in image on a canvas, the white pixels surrounding the image are there too to the image boundries. Any tips on how to prevent this?

推荐答案

import java.awt.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
import javax.imageio.ImageIO;
import java.net.URL;

class ImageTransparencyByColor {

    public static BufferedImage getTransparentImage(
        BufferedImage image, Color transparent) {
        // must have a transparent image
        BufferedImage img = new BufferedImage(
            image.getWidth(),image.getHeight(),BufferedImage.TYPE_INT_ARGB);
        Graphics2D g= img.createGraphics();
        for (int x=0; x<img.getWidth(); x++) {
            for (int y=0; y<img.getHeight(); y++) {
                if (image.getRGB(x,y)!=transparent.getRGB()) {
                    img.setRGB( x,y, image.getRGB(x,y) );
                }
            }
        }
        g.dispose();
        return img;
    }

    public static void main(String[] args) throws Exception {
        URL url = new URL ("http://www.gravatar.com/avatar" +
            "/ab5193916ccf152f96b0a69323e934a1?s=128&d=identicon&r=PG");
        final BufferedImage trans = getTransparentImage(
            ImageIO.read(url), Color.WHITE);
        Runnable r = new Runnable() {
            @Override
            public void run() {
                JLabel gui = new JLabel(new ImageIcon(trans));
                JOptionPane.showMessageDialog(null, gui);
            }
        };
        SwingUtilities.invokeLater(r);
    }
}

这篇关于我想加载没有额外白色像素的图像。我该怎么做呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆