gpt4 book ai didi

java - 如何操作位图中的像素?

转载 作者:搜寻专家 更新时间:2023-11-01 09:44:00 24 4
gpt4 key购买 nike

我正在开发一个类似 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;
}
}

我尝试了两种方法将位图转换为灰度。前者似乎在工作(但我无法理解)而后者则没有。谁能帮我吗?如果有更简单的方法在 Android 中操作图像,请务必提及。

最佳答案

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

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

应该是

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

防止无限循环。

关于java - 如何操作位图中的像素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38677165/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com