I have an image loaded into a Bitmap
object. What I then want to do is grayscale the image that is stored in the Bitmap
object.
I do that with the following function:
public static Bitmap grayscale(Bitmap src)
{
// constant factors
final double GS_RED = 0.299;
final double GS_GREEN = 0.587;
final double GS_BLUE = 0.114;
// create output bitmap
Bitmap bmOut = Bitmap.createBitmap(src.getWidth(), src.getHeight(), src.getConfig());
// pixel information
int A, R, G, B;
int pixel;
// get image size
int width = src.getWidth();
int height = src.getHeight();
// scan through every single pixel
for(int x = 0; x < width; ++x)
{
for(int y = 0; y < height; ++y)
{
// get one pixel color
pixel = src.getPixel(x, y);
// retrieve color of all channels
A = Color.alpha(pixel);
R = Color.red(pixel);
G = Color.green(pixel);
B = Color.blue(pixel);
// take conversion up to one single value
R = G = B = (int)(GS_RED * R + GS_GREEN * G + GS_BLUE * B);
// set new pixel color to output bitmap
bmOut.setPixel(x, y, Color.argb(A, R, G, B));
}
}
// return final image
return bmOut;
}
It works fine, but it's incredibly slow. Not for "small" images like 640x480
. But in my case images are 3264x2448
. This literally takes a few seconds before the operation is complete...
So I'm wondering if scanning through each pixel like I do now is really the best way? Are there any better and faster methods to convert the colors of images?