3

背景画像 (PNG) の色相をプログラムで変更したいと考えています。Androidでこれを行うにはどうすればよいですか?

4

3 に答える 3

6

受け入れられた回答をテストしましたが、残念ながら間違った結果を返します。私はここからこのコードを見つけて修正しました。

// 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;
}
于 2014-09-14T14:08:56.150 に答える
2

リンクされた投稿にはいくつかの良いアイデアがありますが、ColorFilter に使用される行列計算は、(a) 複雑でやり過ぎであり、(b) 結果の色に知覚可能な変化をもたらす可能性があります。

ここでjaninによって提供されたソリューションを変更する - https://stackoverflow.com/a/6222023/1303595 - このバージョンは、Photoshopの「カラー」ブレンドモードに基づいています。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);
}
于 2012-06-26T05:16:27.373 に答える