如何在 android 中像素化位图

How to pixelize a bitmap in android

我一直在搜索,但没有找到关于如何在 android

中像素化位图的问题

例子

注意我不是说模糊

您可以尝试将该图像的大小调整为较小的版本(如果您出于某种原因需要将它的大小设置为与原始图像相同的大小,然后进行备份)

{
    Bitmap original = ...;
    //Calculate proportional size, or make the method accept just a factor of scale.
    Bitmap small = getResigetResizedBitmap(original, smallWidth, smallHeight);
    Bitmap pixelated = getResigetResizedBitmap(small, normalWidth, normalHeight);
   //Recycle small, recycle original if no longer needed.
}

public Bitmap getResizedBitmap(Bitmap bm, int newWidth, int newHeight) {
    int width = bm.getWidth();
    int height = bm.getHeight();
    float scaleWidth = ((float) newWidth) / width;
    float scaleHeight = ((float) newHeight) / height;
    // CREATE A MATRIX FOR THE MANIPULATION
    Matrix matrix = new Matrix();
    // RESIZE THE BIT MAP
    matrix.postScale(scaleWidth, scaleHeight);

    // "RECREATE" THE NEW BITMAP
    Bitmap resizedBitmap = Bitmap.createBitmap(
        bm, 0, 0, width, height, matrix, false);
    return resizedBitmap;
}

代码来自here

像素化图像的最简单方法是使用 "nearest neighbour" algorithm 缩小图像,然后使用相同的算法放大图像。

对图像进行过滤以试图找到平均值会花费更多时间,但实际上并不能提高结果质量,毕竟您确实故意希望图像失真。