灰度算法的应用

package com.bjsxt.util;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class ImageColor {


    /**
     * @Description: 变灰
     * @param  imgPath 图片路径
     * @param  fileUrl 输出图片路径
     * @throws
     */
    public static void inverse(String imgPath, String fileUrl){
        try {
            FileInputStream fileInputStream = new FileInputStream(imgPath);
            BufferedImage image = ImageIO.read(fileInputStream);
            //生成字符图片
            int w = image.getWidth();
            int h = image.getHeight();
            BufferedImage imageBuffer = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);;
            // 绘制字符
            for (int y = 0; y < h; y++) {
                for (int x = 0; x< w; x++) {
                    int rgb = image.getRGB(x, y);
                    int R = (rgb & 0xff0000) >> 16;
                    int G = (rgb & 0x00ff00) >> 8;
                    int B = rgb & 0x0000ff;

                    int gray = (int)(R * 0.299 + G * 0.587 + B * 0.114);

//                    int newPixel=colorToRGB(255-R,255-G,255-B);
                    int newPixel=colorToRGB(gray,gray,gray);


                    imageBuffer.setRGB(x,y,newPixel);
                }
            }
            ImageIO.write(imageBuffer, "png", new File(fileUrl)); //输出图片
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @Description: 颜色转rgb值
     * @throws
     */
    public static int colorToRGB(int red,int green,int blue){
        int newPixel=0;
        newPixel=newPixel << 8;
        newPixel+=red;
        newPixel=newPixel << 8;
        newPixel+=green;
        newPixel=newPixel << 8;
        newPixel+=blue;
        return  newPixel;

    }

    public static void main(String[] args) throws IOException {
        inverse("D:\\灰度算法应用\\白菜.png", "D:\\灰度算法应用\\白菜_gray.png");

    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值