在andriod中写一个从文件中读取图片进行裁剪然后保存到一个文件中
以下是从文件中读取图片进行裁剪并保存到另一个文件中的Android代码:
// 获取文件路径
String filePath = "/sdcard/myImage.jpg";
// 从文件中创建Bitmap对象
Bitmap bitmap = BitmapFactory.decodeFile(filePath);
// 定义裁剪后的宽度和高度
int width = 200;
int height = 200;
// 创建一个Matrix对象,用于调整Bitmap的大小和位置
Matrix matrix = new Matrix();
matrix.postScale((float)width/bitmap.getWidth(), (float)height/bitmap.getHeight());
// 裁剪Bitmap对象
Bitmap croppedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
// 保存裁剪后的Bitmap到文件中
String croppedFilePath = "/sdcard/myCroppedImage.jpg";
try {
    FileOutputStream out = new FileOutputStream(croppedFilePath);
    croppedBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
    out.flush();
    out.close();
} catch (Exception e) {
    e.printStackTrace();
}
在上面的代码中,我们首先获取要裁剪的图片的文件路径,然后使用BitmapFactory类的decodeFile()方法从文件中创建一个Bitmap对象。接着,我们定义裁剪后的宽度和高度,并创建一个Matrix对象,用于调整Bitmap的大小和位置。然后,我们使用Bitmap类的createBitmap()方法裁剪Bitmap对象。最后,我们将裁剪后的Bitmap保存到另一个文件中。
请注意,上面的代码中使用了硬编码的文件路径,因此需要根据实际情况进行修改。此外,为了在Android中读写文件,需要在AndroidManifest.xml文件中添加以下权限:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
``
 
原文地址: https://www.cveoy.top/t/topic/fs0F 著作权归作者所有。请勿转载和采集!