bitmap转换成点阵数据

public void convertBitmapToDotMatrix(Bitmap bitmap1) {

// 获取存储路径

File dir = new File(context.getFilesDir(), "print");

if (!dir.exists()) {

dir.mkdirs();

}



// 格式化文件名

String fileName = String.valueOf(System.currentTimeMillis());



// 输出文件路径

File picFile = new File(dir, fileName + ".txt");

Logs.e("printBitmap Files Dir", dir.getAbsolutePath());



// 加载图像资源(以示例资源 R.raw.korean 为例)

// InputStream inputStream = this.getResources().openRawResource(R.raw.korean);

// Bitmap bitmap1 = BitmapFactory.decodeStream(inputStream);



if (bitmap1 == null) {

Logs.e("printBitmap", "Bitmap decoding failed!");

return;

}



int width = bitmap1.getWidth();

int height = bitmap1.getHeight();

int threshold = 128;



// 将图像转换为点阵数据

int[][] data = new int[width][height];

try (FileWriter writer = new FileWriter(picFile)) {

for (int j = 0; j < height; j++) { // 遍历高度(行)

for (int i = 0; i < width; i++) { // 遍历宽度(列)

int pixel = bitmap1.getPixel(i, j);

// 转为灰度值

int gray = (Color.red(pixel) + Color.green(pixel) + Color.blue(pixel)) / 3;

// 判断是否低于阈值

data[i][j] = gray < threshold ? 1 : 0;

// 写入文件

writer.write(data[i][j] + " ");

}

// 换行

writer.write("\n");

}

} catch (IOException e) {

e.printStackTrace();

}

}

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.File android.content.Context.getFilesDir()' on a null object reference

File dir = new File(context.getFilesDir(), "print"); 

 加上,context 否则会出现NullPointerException

你可能感兴趣的:(java)