Android Realization of Image Grayscale Linear Grayscale Change and Binary Processing Method
- 2021-10-24 23:41:52
- OfStack
1. Image grayscale:
public Bitmap bitmap2Gray(Bitmap bmSrc) {
// Get the length and width of the picture
int width = bmSrc.getWidth();
int height = bmSrc.getHeight();
// Create a gray image of the target
Bitmap bmpGray = null;
bmpGray = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
// Create a canvas
Canvas c = new Canvas(bmpGray);
Paint paint = new Paint();
ColorMatrix cm = new ColorMatrix();
cm.setSaturation(0);
ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm);
paint.setColorFilter(f);
c.drawBitmap(bmSrc, 0, 0, paint);
return bmpGray;
}
2. Carry out linear gray level change on the image
public Bitmap lineGrey(Bitmap image) {
// Get the width and length of the image
int width = image.getWidth();
int height = image.getHeight();
// Create a linear pull-up grayscale image
Bitmap linegray = null;
linegray = image.copy(Config.ARGB_8888, true);
// The pixels of the image are processed cyclically in turn
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
// Get the pixel value of each point
int col = image.getPixel(i, j);
int alpha = col & 0xFF000000;
int red = (col & 0x00FF0000) >> 16;
int green = (col & 0x0000FF00) >> 8;
int blue = (col & 0x000000FF);
// Increases the brightness of the image
red = (int) (1.1 * red + 30);
green = (int) (1.1 * green + 30);
blue = (int) (1.1 * blue + 30);
// Processing the image pixel out of bounds
if (red >= 255)
{
red = 255;
}
if (green >= 255) {
green = 255;
}
if (blue >= 255) {
blue = 255;
}
// New ARGB
int newColor = alpha | (red << 16) | (green << 8) | blue;
// Set the for the new image RGB Value
linegray.setPixel(i, j, newColor);
}
}
return linegray;
}
3. Binary the image
public Bitmap gray2Binary(Bitmap graymap) {
// Get the width and length of the graph
int width = graymap.getWidth();
int height = graymap.getHeight();
// Create 2 Valuable image
Bitmap binarymap = null;
binarymap = graymap.copy(Config.ARGB_8888, true);
// The pixels of the image are processed in turn
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
// Get the value of the current pixel
int col = binarymap.getPixel(i, j);
// Get alpha The value of the channel
int alpha = col & 0xFF000000;
// Get the pixels of the image RGB Value of
int red = (col & 0x00FF0000) >> 16;
int green = (col & 0x0000FF00) >> 8;
int blue = (col & 0x000000FF);
// With a formula X = 0.3 × R+0.59 × G+0.11 × B Calculate X Replace the original RGB
int gray = (int) ((float) red * 0.3 + (float) green * 0.59 + (float) blue * 0.11);
// Perform an image 2 Valuation processing
if (gray <= 95) {
gray = 0;
} else {
gray = 255;
}
// New ARGB
int newColor = alpha | (gray << 16) | (gray << 8) | gray;
// Set the current pixel value of the new image
binarymap.setPixel(i, j, newColor);
}
}
return binarymap;
}