在android中将位图转换为sepia

时间:2010-11-10 04:09:42

标签: android android-image

有没有办法将Bitmap转换为棕褐色? 我知道转换为grayScale是在ColorMatrix中设置setSaturation。 但是棕褐色呢?

3 个答案:

答案 0 :(得分:19)

如果您有图像实例,则可以使用ColorMartix在棕褐色中绘制它。让我来描述一下如何使用Drawable来实现这一目标。

public static void setSepiaColorFilter(Drawable drawable) {
  if (drawable == null)
    return;

  final ColorMatrix matrixA = new ColorMatrix();
  // making image B&W
  matrixA.setSaturation(0);

  final ColorMatrix matrixB = new ColorMatrix();
  // applying scales for RGB color values
  matrixB.setScale(1f, .95f, .82f, 1.0f);
  matrixA.setConcat(matrixB, matrixA);

  final ColorMatrixColorFilter filter = new ColorMatrixColorFilter(matrixA);
  drawable.setColorFilter(filter);
}

示例项目已从Bitbucket移至GitHub。请检查Release section下载APK二进制文件以进行测试而不进行编译。

enter image description here

答案 1 :(得分:5)

我知道答案,但也许有些人有其他更好的解决方案..

public Bitmap toSephia(Bitmap bmpOriginal)
{        
    int width, height, r,g, b, c, gry;
    height = bmpOriginal.getHeight();
    width = bmpOriginal.getWidth();
    int depth = 20;

    Bitmap bmpSephia = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bmpSephia);
    Paint paint = new Paint();
    ColorMatrix cm = new ColorMatrix();
    cm.setScale(.3f, .3f, .3f, 1.0f);   
    ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm);
    paint.setColorFilter(f);
    canvas.drawBitmap(bmpOriginal, 0, 0, paint);
    for(int x=0; x < width; x++) {
        for(int y=0; y < height; y++) {
            c = bmpOriginal.getPixel(x, y);

            r = Color.red(c);
            g = Color.green(c);
            b = Color.blue(c);

            gry = (r + g + b) / 3;
            r = g = b = gry;

            r = r + (depth * 2);
            g = g + depth;

            if(r > 255) {
              r = 255;
            }
            if(g > 255) {
              g = 255;
            }
            bmpSephia.setPixel(x, y, Color.rgb(r, g, b));
        }
    }      
    return bmpSephia;
}

答案 2 :(得分:0)

我在the OP's answer进行了改进。与the ColorMatrix method相比,这种运行速度相当快,但产生了更好的棕色调。 (在我看来)

public Bitmap toSepiaNice(Bitmap color) {
    int red, green, blue, pixel, gry;
    int height = color.getHeight();
    int width = color.getWidth();
    int depth = 20;

    Bitmap sepia = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);

    int[] pixels = new int[width * height];
    color.getPixels(pixels, 0, width, 0, 0, width, height);
    for (int i = 0; i < pixels.length; i++) {
        pixel = pixels[i];

        red = (pixel >> 16) & 0xFF;
        green = (pixel >> 8) & 0xFF;
        blue = pixel & 0xFF;

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

        red += (depth * 2);
        green += depth;

        if (red > 255)
            red = 255;
        if (green > 255)
            green = 255;
        pixels[i] = (0xFF << 24) | (red << 16) | (green << 8) | blue;
    }
    sepia.setPixels(pixels, 0, width, 0, 0, width, height);
    return sepia;
}