2012-04-20 64 views
3

我正在寻找以编程方式更改背景图像(PNG)的色调。这怎么能在Android上完成?Android:如何更改图像的色调?

+1

检查这个帖子http://stackoverflow.com/questions/4354939/understanding-the-use-of-colormatrix-and-colormatrixcolorfilter-to-modify -a-draw – JRaymond 2012-04-20 23:07:06

回答

2

链接的柱具有一些好的想法,但是用于ColorFilter的矩阵数学可以是(a)中复合矫枉过正,和(b)中所得到的颜色引入可察觉的变化。

在此处修改janin给出的解决方案 - https://stackoverflow.com/a/6222023/1303595 - 我在Photoshop's 'Color' blend mode上根据此版本。这似乎避免因PorterDuff.Mode.Multiply图像变暗,而且运作非常良好的色彩着色去饱和/人造黑&白图像不失大的反差。

/* 
* Going for perceptual intent, rather than strict hue-only change. 
* This variant based on Photoshop's 'Color' blending mode should look 
* better for tinting greyscale images and applying an all-over color 
* without tweaking the contrast (much) 
*  Final color = Target.Hue, Target.Saturation, Source.Luma 
* Drawback is that the back-and-forth color conversion introduces some 
* error each time. 
*/ 
public void changeHue (Bitmap bitmap, int hue, int width, int height) { 
    if (bitmap == null) { return; } 
    if ((hue < 0) || (hue > 360)) { return; } 

    int size = width * height; 
    int[] all_pixels = new int [size]; 
    int top = 0; 
    int left = 0; 
    int offset = 0; 
    int stride = width; 

    bitmap.getPixels (all_pixels, offset, stride, top, left, width, height); 

    int pixel = 0; 
    int alpha = 0; 
    float[] hsv = new float[3]; 

    for (int i=0; i < size; i++) { 
     pixel = all_pixels [i]; 
     alpha = Color.alpha (pixel); 
     Color.colorToHSV (pixel, hsv); 

     // You could specify target color including Saturation for 
     // more precise results 
     hsv [0] = hue; 
     hsv [1] = 1.0f; 

     all_pixels [i] = Color.HSVToColor (alpha, hsv); 
    } 

    bitmap.setPixels (all_pixels, offset, stride, top, left, width, height); 
} 
4

我测试了接受的答案,不幸的是它返回了错误的结果。我发现,从here修改这个代码的正常工作:

// hue-range: [0, 360] -> Default = 0 
public static Bitmap hue(Bitmap bitmap, float hue) { 
    Bitmap newBitmap = bitmap.copy(bitmap.getConfig(), true); 
    final int width = newBitmap.getWidth(); 
    final int height = newBitmap.getHeight(); 
    float [] hsv = new float[3]; 

    for(int y = 0; y < height; y++){ 
     for(int x = 0; x < width; x++){ 
      int pixel = newBitmap.getPixel(x,y); 
      Color.colorToHSV(pixel,hsv); 
      hsv[0] = hue; 
      newBitmap.setPixel(x,y,Color.HSVToColor(Color.alpha(pixel),hsv)); 
     } 
    } 

    bitmap.recycle(); 
    bitmap = null; 

    return newBitmap; 
} 
+0

此代码有效,但速度很慢。任何想法优化? – 2018-02-25 18:31:34