在保存到android的内部存储之前如何更改jpg图像的位深?

时间:2018-07-26 08:53:16

标签: android image-compression image-conversion bit-depth

下面的图像取自Officelens,它们转换了图像的位深,在顶部形成了清晰的黑白图像,在底部显示了原始图像:

enter image description here

但是当我尝试转换时,我得到的输出如下:

enter image description here

以上结果是使用tif转换库完成的 我尝试过的代码如下:

 private void takePicture() {
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    File folderPath = new File(Environment.getExternalStorageDirectory() + "/OCR");

    if (!folderPath.exists()) {
        if (folderPath.mkdir()) ; //directory is created;
    } else {
        File photo = new File(folderPath, "OCRPIC" + UUID.randomUUID().toString().substring(0, 5) + ".jpg");
        imageUri = FileProvider.getUriForFile(MainActivity.this,
                BuildConfig.APPLICATION_ID + ".provider", photo);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        startActivityForResult(intent, PHOTO_REQUEST);
        }
}

当我将图像从相机保存到内部存储时,在检索时,我将进行颜色压缩转换,代码如下所示,

 TiffConverter.ConverterOptions options = new TiffConverter.ConverterOptions();
    options.throwExceptions = false;
    options.availableMemory = 1 * 1024 * 1024;
    options.compressionScheme = CompressionScheme.LZW;
    options.readTiffDirectory = 1;
    TiffConverter.convertToTiff(path, Environment.getExternalStorageDirectory() + "/OCR"+"/"+path.substring(path.lastIndexOf("/")+1).substring(0,11)+".jpg", options,null);

我想要实现Office Lens产生的输出。

1 个答案:

答案 0 :(得分:0)

Try below code to decrease color depth 

public static Bitmap decreaseColorDepth(Bitmap src, int bitOffset) {
    // get image size
    int width = src.getWidth();
    int height = src.getHeight();
    // create output bitmap
    Bitmap bmOut = Bitmap.createBitmap(width, height, src.getConfig());
    // color information
    int A, R, G, B;
    int pixel;

    // scan through all pixels
    for(int x = 0; x < width; ++x) {
        for(int y = 0; y < height; ++y) {
            // get pixel color
            pixel = src.getPixel(x, y);
            A = Color.alpha(pixel);
            R = Color.red(pixel);
            G = Color.green(pixel);
            B = Color.blue(pixel);

            // round-off color offset
            R = ((R + (bitOffset / 2)) - ((R + (bitOffset / 2)) % bitOffset) - 1);
            if(R < 0) { R = 0; }
            G = ((G + (bitOffset / 2)) - ((G + (bitOffset / 2)) % bitOffset) - 1);
            if(G < 0) { G = 0; }
            B = ((B + (bitOffset / 2)) - ((B + (bitOffset / 2)) % bitOffset) - 1);
            if(B < 0) { B = 0; }

            // set pixel color to output bitmap
            bmOut.setPixel(x, y, Color.argb(A, R, G, B));
        }
    }

    // return final image
    return bmOut;
}