如何操作位图中的像素?

时间:2016-07-30 18:24:31

标签: java android bitmap

我正在开发一个类似Instagram的应用程序,用于学习图像处理和android。但是我被困住了,我在应用程序中实现灰度过滤器时遇到了问题。我现在尝试一种简单的方法将位图中的单个像素转换为灰度。

这是我写的整个课程,以便将各种过滤器应用于图像:

package com.dosa2.photoeditor.ImageEffects;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Paint;

public class ImageEffects {

    Bitmap bitmap;
    int width, height;

    public ImageEffects(Bitmap bitmap) {
        this.bitmap = bitmap;
        width = bitmap.getWidth();
        height = bitmap.getHeight();
    }

    public Bitmap toGrayscale() {

        Bitmap resultBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(resultBitmap);
        Paint p = new Paint();
        ColorMatrix cm = new ColorMatrix();
        cm.setSaturation(0);
        ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm);
        p.setColorFilter(f);
        c.drawBitmap(bitmap, 0, 0, p);

        return resultBitmap;
    }

    public Bitmap toGrayscale2() {
        Bitmap resultBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);

        for(int i=0;i<height;i++) {
            for (int j=0;i<width;j++) {
                int c = bitmap.getPixel(i,j);
                resultBitmap.setPixel(i, j, (Color.red(c)+Color.blue(c)+Color.green(c)/3));
            }
        }

        return resultBitmap;
    }
}

我尝试了两种将Bitmap转换为灰度的方法。前者似乎有效(但我无法理解)而后者则不然。 谁能帮我吗?如果在Android中操作图像有一种更简单的方法,那就提一下。

2 个答案:

答案 0 :(得分:1)

错误(或至少其中一个......)在你的一个for循环中:

for (int j=0;i<width;j++)

应该是

for (int j=0;j<width;j++)

防止无限循环。

答案 1 :(得分:0)

你的方法&#34; toGrayscale&#34;我正在使用ColorMatrix类,我认为内部使用RenderScript API来进行渲染(或者至少使用GPU着色器)。 RenderScript是Android的计算API(类似于OpenCL,实际上是一个可以在OpenCL上运行的层),所以你不是只使用CPU来进行颜色过滤,你甚至使用GPU或您的设备可能具有的其他DSP。第二种方法&#34; toGrayscale2&#34;因为您只使用CPU将Bitmap转换为灰度(逐个像素)而且您不应该使用它,所以速度较慢。检查this presentation(它非常有趣),以便更多地了解您的第一种方法是如何工作的,链接指向第12页的颜色过滤,但您应该完全查看它以便明白了。