将背景为白色图片转为png格式的透明图片

在程序设计及网站搭建过程中我们经常会用到png格式的背景透明图片,在找素材过程中经常遇到心仪的图片却不是png格式的透明背景图片。本次设计就是解决将背景为白色(rgb为:r[210-255],g[210-255],b[210-255])的背景转为png格式的透明图片。
程序包含两个类:PictureProcessing和Main、
PictureProcessing类:
构造方法:public PictureProcessing(String image)
说明:image为将要处理的图片地址
方法:public BufferedImage getChangecolorl()
说明:将一个png格式图片的白色背景变为透明
public String getType()
说明:判断图片编码格式
public BufferedImage outputImage()
说明:创建一个png图片与处理的图片大小一致
Main类:
构造方法:public main()
方法:mian()
说明:定义一个窗体对象JFrame,在其添加一个JTextField和JButton。JTextField实现将图片拖入返回图片路径。JButton实现鼠标点击执行图片处理。
内部类:static class MyListener
说明:内部类实现ActionListener接口,鼠标点击按钮后的事件
主要代码如下:

public class Main {
    static String lujing;
    private static JFrame f;
    public static void main(String[] args) {
        JTextField field ;
        File dir=new File("");
        String topname= "./src/Imagebackgroundtransparencyprocessing/顶部图标.png";//顶部图标路径//顶部图标路径
        File ni=new File(String.valueOf(topname));
        BufferedImage top=null;//顶部图标
        try {
            top=ImageIO.read(ni);
        } catch (IOException e) {
            e.printStackTrace();
        }
        f = new JFrame("图片背景处理(使白色背景变透明)");//定义一个窗体对象f
        f.setSize(800, 500);//窗体屏幕长和宽
        f.setLocationRelativeTo(null);//窗口置于屏幕中央
        f.setIconImage(top);
        f.setResizable(false);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//点击窗口的关闭按钮时,程序关闭
        //否则程序仍然在后台运行
        f.setLayout(new FlowLayout(FlowLayout.CENTER,30,30));//创建一个新的流布局管理器,
        //具有指定的对齐方式以及指定的水平和垂直间隙

        //底部按钮
        JButton a = new JButton("点 击 进 行 图 片 处 理(仅支持jpg、jpeg、png、bmp格式!)");//定义一个按钮对象a
        a.setPreferredSize(new Dimension(30,40));
        a.setBorderPainted(false);
        a.setFocusPainted(false);//去掉按钮文字周围的虚线框
        a.setBorder(null);//去掉背景色
        Font font=new Font("黑体",Font.PLAIN,18);
        a.setFont(font);
        a.setForeground(Color.black);
        Color n1=new Color(80,100,255);
        a.setBackground(n1);
        a.addActionListener(new MyListener());//为按钮添加一个实现ActionListener接口的对象

        //创建一个文本,实现文件拖入返回路径
        field = new JTextField("将图片拖入此处");
        field.setFont(font);
        field.setCaretColor(Color.black);
        field.setPreferredSize(new Dimension(700, 340));//设置文本框长宽
        field.setEnabled(false);//设置文本不可变
        Color n=new Color(193,193,193);
        field.setBackground(n);
        field.setTransferHandler(new TransferHandler() {//实现文件拖入显示路径,并将路径赋值给lujing
            private static final long serialVersionUID = 1L;

            @Override
            public boolean importData(JComponent comp, Transferable t) {
                try {
                    Object o = t.getTransferData(DataFlavor.javaFileListFlavor);

                    String filepath = o.toString();
                    if (filepath.startsWith("[")) {
                        filepath = filepath.substring(1);
                    }
                    if (filepath.endsWith("]")) {
                        filepath = filepath.substring(0, filepath.length() - 1);
                    }
                    field.setText("文件的路径为:"+filepath);
                    lujing = filepath;//路径赋值
                    return true;
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return false;
            }

            @Override
            public boolean canImport(JComponent comp, DataFlavor[] flavors) {
                for (int i = 0; i < flavors.length; i++) {
                    if (DataFlavor.javaFileListFlavor.equals(flavors[i])) {
                        return true;
                    }
                }
                return false;
            }
        });
        JPanel panel = new JPanel(new BorderLayout(50, 10));//设置间隙
        panel.add(field, BorderLayout.NORTH);//将field放置在北面
        panel.add(a, BorderLayout.SOUTH);//将a放置南面
        f.add(panel);//将组件a添加至容器
        f.setVisible(true);//设置窗体可见
    }

    //点击确定按钮后操作
    static class MyListener implements ActionListener {//定义内部类实现ActionListener接口

        @Override
        public void actionPerformed(ActionEvent e) {//重写actionPerformed()方法
            PictureProcessing ni = new PictureProcessing(lujing);
            boolean T=false;
            try {
                ImageIO.write(ni.getChangecolorl(), "png", new File(lujing.substring(0, lujing.indexOf(".") ) + "(甘肃不大出品).png"));
                T=true;
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            System.out.println(lujing.substring(0, lujing.indexOf(".") + 1) + "png");
            if(T==true){
                JOptionPane ttt=new JOptionPane();
                String[] options = { "确定", "取消" };
                ttt.showOptionDialog(null, "已完成转换!", "提示",
                        JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE,
                        null, options, options[0]);
            }
        }
    }
}

PictureProcessing类的实现:

public class PictureProcessing {
    private String image;

    /**
     * 以下的方法是将一个png格式图片的白色背景变为透明。
     *
     * @return:
     */
    public BufferedImage getChangecolorl() {//传的参数为图片地址
        int[] rgb = new int[3];
        File file = new File(image);
        BufferedImage bu = null;
        /**
         * 判断传入的图片是否为png编码格式
         * 如不是则新建一个与传入图片大小相等的png图片
         */
        if (getType() == "png") {
            try {
                bu = ImageIO.read(file);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            bu = outputImage();
        }
        BufferedImage bi = null;
        try {
            bi = ImageIO.read(file);
        } catch (Exception e) {
            e.printStackTrace();
        }
        int width = bi.getWidth();
        int height = bi.getHeight();
        int minx = bi.getMinX();
        int miny = bi.getMinY();
        for (int i = minx; i < width; i++) {
            for (int j = miny; j < height; j++) {
                int pixel = bi.getRGB(i, j); // 下面三行代码将一个数字转换为RGB数字
                int alpha;//无符号右移获取alpha值
                rgb[0] = (pixel & 0xff0000) >> 16;
                rgb[1] = (pixel & 0xff00) >> 8;
                rgb[2] = (pixel & 0xff);
                alpha = (pixel & 0xff000000) >>> 24;
                if (rgb[0] == 66) {
                    if (rgb[1] == 142) {
                        if (rgb[2] == 218) {
                            pixel = ((alpha + 1) << 24) | (pixel & 0x00ffffff);
                        }
                    }
                }//如果rgb的范围处于240-250,则将其转为图片;
                bu.setRGB(i, j, pixel);//将处理后的像素点写回
            }
        }
        return bu;
    }

    /**
     * 判断图片的编码格式
     *
     * @return;图片类型
     */
    public String getType() {
        File oo = new File(image);
        ImageInputStream iis = null;
        try {
            iis = ImageIO.createImageInputStream(oo);
        } catch (IOException e) {
            e.printStackTrace();
        }
        Iterator<ImageReader> iterator = ImageIO.getImageReaders(iis);
        while (iterator.hasNext()) {
            ImageReader reader = (ImageReader) iterator.next();
            try {
                return reader.getFormatName();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 创建一个png图片
     * @return
     */
    public BufferedImage outputImage() {
        BufferedImage g = null;
        try {
            g = ImageIO.read(new File(this.image));
        } catch (IOException e) {
            e.printStackTrace();
        }
        BufferedImage bnn = new BufferedImage(g.getWidth(), g.getHeight(), BufferedImage.TYPE_4BYTE_ABGR);
        Graphics2D g2d = bnn.createGraphics();
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE);
        g2d.fillRect(0, 0, 0, 0);
        g2d.translate(bnn.getWidth() / 2, bnn.getHeight() / 2);
        g2d.dispose();
        bnn.flush();
        return bnn;
    }

    /**
     * 构造方法,获取图片文件地址
     * @param image
     */
    public PictureProcessing(String image) {
        this.image = image;
    }
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

面试被虐的小lala

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值