android 如何使图片变灰
------解决方案--------------------
是把彩色图像转换为灰度图是不是?
我帮你写了一段代码,测试通过。方法的两个参数分别是源文件,目标文件在Android内的路径位置。
要注意的是,存取SD卡的话,必须在AndroidManifest.xml文件中加上一行
<uses-permission android:name = "android.permission.WRITE_EXTERNAL_STORAGE" />
否则创建文件会失败。
- Java code
package com.example; import java.io.*; import android.graphics.*; import android.graphics.Bitmap.CompressFormat; public class ReadImage { public static void toGrayImage(String source, String dest) { try { Bitmap bitmap = BitmapFactory.decodeFile(source); int width = bitmap.getWidth(); int height = bitmap.getHeight(); Bitmap grayImg = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); // Canvas canvas = new Canvas(grayImg); Paint paint = new Paint(); ColorMatrix colorMatrix = new ColorMatrix(); colorMatrix.setSaturation(0); ColorMatrixColorFilter colorMatrixFilter = new ColorMatrixColorFilter( colorMatrix); paint.setColorFilter(colorMatrixFilter); canvas.drawBitmap(bitmap, 0, 0, paint); // canvas. File file = new File(dest); boolean success = file.createNewFile(); FileOutputStream stream = new FileOutputStream(file); grayImg.compress(CompressFormat.JPEG, 100, stream); stream.flush(); stream.close(); bitmap.recycle(); grayImg.recycle(); } catch (Exception e) { @SuppressWarnings("unused") String msg = e.getMessage(); } } }