天天看點

Java圖檔透明化操作

public class ClearImageHelper {

public static BufferedImage cleanImage(BufferedImage bufferedImage)throws IOException{  

        int h = bufferedImage.getHeight();  

        int w = bufferedImage.getWidth();  

        // 灰階化  

        int[][] gray = new int[w][h];  

        for (int x = 0; x < w; x++){  

            for (int y = 0; y < h; y++){  

                int argb = bufferedImage.getRGB(x, y);  

                // 圖像加亮(調整亮度識别率非常高)  

                int r = (int) (((argb >> 16) & 0xFF) * 1.1 + 30);  

                int g = (int) (((argb >> 8) & 0xFF) * 1.1 + 30);  

                int b = (int) (((argb >> 0) & 0xFF) * 1.1 + 30);  

                if (r >= 255){  

                    r = 255;  

                }  

                if (g >= 255){  

                    g = 255;  

                }  

                if (b >= 255){  

                    b = 255;  

                }  

                gray[x][y] = (int) Math.pow((Math.pow(r, 2.2) * 0.2973 + Math.pow(g, 2.2)* 0.6274 + Math.pow(b, 2.2) * 0.0753), 1 / 2.2);  

            }  

        }  

        // 二值化  

        int threshold = ostu(gray, w, h);  

        BufferedImage binaryBufferedImage = new BufferedImage(w, h,BufferedImage.TYPE_BYTE_BINARY);  

        for (int x = 0; x < w; x++){  

            for (int y = 0; y < h; y++){  

                if (gray[x][y] > threshold){  

                    gray[x][y] |= 0x00FFFF;  

                } else{  

                    gray[x][y] &= 0xFF0000;  

                }  

                binaryBufferedImage.setRGB(x, y, gray[x][y]);  

            }  

        }  

        return binaryBufferedImage;

    }  

public static int ostu(int[][] gray, int w, int h){  

        int[] histData = new int[w * h];  

        // Calculate histogram  

        for (int x = 0; x < w; x++){  

            for (int y = 0; y < h; y++){  

                int red = 0xFF & gray[x][y];  

                histData[red]++;  

            }  

        }  

        // Total number of pixels  

        int total = w * h;  

        float sum = 0;  

        for (int t = 0; t < 256; t++)  

            sum += t * histData[t];  

        float sumB = 0;  

        int wB = 0;  

        int wF = 0;  

        float varMax = 0;  

        int threshold = 0;  

        for (int t = 0; t < 256; t++){  

            wB += histData[t]; // Weight Background  

            if (wB == 0)  

                continue;  

            wF = total - wB; // Weight Foreground  

            if (wF == 0)  

                break;  

            sumB += (float) (t * histData[t]);  

            float mB = sumB / wB; // Mean Background  

            float mF = (sum - sumB) / wF; // Mean Foreground  

            // Calculate Between Class Variance  

            float varBetween = (float) wB * (float) wF * (mB - mF) * (mB - mF);  

            // Check if new maximum found  

            if (varBetween > varMax){  

                varMax = varBetween;  

                threshold = t;  

            }  

        }  

        return threshold;  

    }  

    //圖檔灰階,黑白  

    public static BufferedImage gray(BufferedImage src) {  

    ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_GRAY);  

    ColorConvertOp op = new ColorConvertOp(cs, null);  

    src = op.filter(src, null);  

        return src;

    }  

public static BufferedImage transparentImage(String  srcImageFile,int alpha) {  

    BufferedImage bufferedImage=null;

    try {  

    //讀取圖檔  

    FileInputStream stream = new FileInputStream(new File(srcImageFile));// 指定要讀取的圖檔  

    // 定義一個位元組數組輸出流,用于轉換數組  

    ByteArrayOutputStream os = new ByteArrayOutputStream();  

    byte[] data =new byte[1024];// 定義一個1K大小的數組  

    while (stream.read(data) != -1) {  

    os.write(data);  

    }  

        ImageIcon imageIcon = new ImageIcon(os.toByteArray());  

        bufferedImage = new BufferedImage(imageIcon.getIconWidth(), imageIcon.getIconHeight(),  

        BufferedImage.TYPE_4BYTE_ABGR);

        Graphics2D g2D = (Graphics2D) bufferedImage.getGraphics();  

        g2D.drawImage(imageIcon.getImage(), 0, 0, imageIcon.getImageObserver());  

        //判讀透明度是否越界  

        if (alpha < 0) {

        alpha = 0;

        } else if (alpha > 10) {

        alpha = 10;

        }

        int c = bufferedImage.getRGB(3, 3);

        // 循環每一個像素點,改變像素點的Alpha值

        for (int j1 = bufferedImage.getMinY(); j1 < bufferedImage.getHeight(); j1++) {

        for (int j2 = bufferedImage.getMinX(); j2 < bufferedImage.getWidth(); j2++) {

        int rgb = bufferedImage.getRGB(j2, j1);

        if(c==rgb){

        rgb = rgb & 0x00ffffff;

        }else{

        rgb = ((alpha * 255 / 10) << 24) | (rgb & 0x00ffffff);  

        }

        bufferedImage.setRGB(j2, j1, rgb);  

        }  

        }  

        g2D.drawImage(bufferedImage, 0, 0, imageIcon.getImageObserver());  

    } catch (Exception e) {

    e.printStackTrace();

    }finally {

return bufferedImage;

}

    }  

    public static String rootUrl = System.getProperty("user.dir")+File.separator;

    public static String FILE_DIR="C:\\Users\\wzk\\Desktop\\"; 

    public static void main(String[] args) throws IOException{  

        File testDataDir = new File(FILE_DIR+"1.png");//去噪  

        BufferedImage textImage =ImageIO.read(new FileInputStream(testDataDir));

//        cleanImage(textImage);  

        BufferedImage gray = gray(textImage);//灰階化

        ImageIO.write(gray, "png", new File(FILE_DIR+"2.png"));

    }  

}