android 灰度图 黑白图

  /**
     * 转为二值图像
     *
     * @param bmp
     *            原图bitmap
     * @return
     */
    public static Bitmap convertToBMW(Bitmap bmp) {

        int width = bmp.getWidth(); // 获取位图的宽
        int height = bmp.getHeight(); // 获取位图的高
        int[] pixels = new int[width * height]; // 通过位图的大小创建像素点数组

        bmp.getPixels(pixels, 0, width, 0, 0, width, height);

        for (int i = 0; i < height; i++) {
            for (int j = 0; j < width; j++) {
                int grey = pixels[width * i + j];
                // 分离三原色
                int alpha = ((grey & 0xFF000000) >> 24);

                int red = ((grey & 0x00FF0000) >> 16);
                int green = ((grey & 0x0000FF00) >> 8);
                int blue = (grey & 0x000000FF);

                int avg = (red + green +blue)/3;

                avg  =  getTowValue(avg);//去掉 为灰度图

                pixels[width * i + j] = alpha << 24 | avg << 16 | avg << 8
                        | avg;

            }
        }
        // 新建图片
        Bitmap newBmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        // 设置图片数据
        newBmp.setPixels(pixels, 0, width, 0, 0, width, height);

        Bitmap resizeBmp = ThumbnailUtils.extractThumbnail(newBmp, width, height);
        return resizeBmp;
    }
    static int getTwoValue(int value){
        // 设定二值化的域值,默认值为100
        if (value>100){
            return 255;
        }else {
            return 0;
        }

    }

你可能感兴趣的:(android)