You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Xamarin Android如何将相机拍摄的照片保存为300DPI格式

Xamarin.Android 照片修改为300DPI解决方案

以下方案适配Visual Studio 2019开发环境,无需引入第三方依赖库。

方案1:仅修改DPI元数据(推荐,无画质损失)

相机输出的96DPI仅为EXIF元数据标识,不会影响原图像素精度。修改元数据不会改变照片内容,完全满足证据类应用的合规要求,处理速度极快。

  • 先引用所需命名空间:
using Android.Media;
using Android.Graphics;
using System.IO;
  • 核心处理代码:
// 替换为你的照片实际存储路径
string originalPhotoPath = "/storage/emulated/0/DCIM/Evidence/capture_photo.jpg";
string outputPhotoPath = Path.Combine(Path.GetDirectoryName(originalPhotoPath), 
    $"{Path.GetFileNameWithoutExtension(originalPhotoPath)}_300dpi.jpg");

// 加载原图
Bitmap originalBitmap = BitmapFactory.DecodeFile(originalPhotoPath);
// 无损压缩保存新文件
using (FileStream outputStream = new FileStream(outputPhotoPath, FileMode.Create))
{
    originalBitmap.Compress(Bitmap.CompressFormat.Jpeg, 100, outputStream);
}
originalBitmap.Recycle();

// 修改EXIF中的DPI配置
ExifInterface exif = new ExifInterface(outputPhotoPath);
// 设置X/Y方向300DPI,格式为分数表示
exif.SetAttribute(ExifInterface.TagXResolution, "300/1");
exif.SetAttribute(ExifInterface.TagYResolution, "300/1");
// 分辨率单位设置为英寸(1=英寸,2=厘米)
exif.SetAttribute(ExifInterface.TagResolutionUnit, "1");
exif.SaveAttributes();

处理完成的照片在系统属性、Photoshop等工具中都会显示为300DPI,像素和原图完全一致。

方案2:重采样像素匹配300DPI物理尺寸(按需使用)

如果需要按照300DPI标准调整实际像素大小(比如要求打印尺寸为46英寸时,像素需要达到12001800),可使用重采样方案:

string originalPhotoPath = "/storage/emulated/0/DCIM/Evidence/capture_photo.jpg";
string outputPhotoPath = Path.Combine(Path.GetDirectoryName(originalPhotoPath), 
    $"{Path.GetFileNameWithoutExtension(originalPhotoPath)}_resized_300dpi.jpg");

Bitmap originalBitmap = BitmapFactory.DecodeFile(originalPhotoPath);
// 按300DPI换算新尺寸,此处以4*6英寸为例,可根据业务需求调整换算逻辑
int newWidth = (int)(4 * 300);
int newHeight = (int)(6 * 300);
// 高精度重采样
Bitmap resizedBitmap = Bitmap.CreateScaledBitmap(originalBitmap, newWidth, newHeight, true);

using (FileStream outputStream = new FileStream(outputPhotoPath, FileMode.Create))
{
    resizedBitmap.Compress(Bitmap.CompressFormat.Jpeg, 100, outputStream);
}
originalBitmap.Recycle();
resizedBitmap.Recycle();

// 同步修改EXIF DPI标识
ExifInterface exif = new ExifInterface(outputPhotoPath);
exif.SetAttribute(ExifInterface.TagXResolution, "300/1");
exif.SetAttribute(ExifInterface.TagYResolution, "300/1");
exif.SetAttribute(ExifInterface.TagResolutionUnit, "1");
exif.SaveAttributes();

注意事项

  • 适配Android 10及以上版本时,访问公共目录照片需要申请MANAGE_EXTERNAL_STORAGE权限,或使用存储访问框架(SAF)操作文件,避免权限报错。
  • 证据类应用建议保持压缩质量为100,避免画质损失影响证据效力。
  • Bitmap处理完成后必须调用Recycle()方法释放内存,避免出现内存溢出问题。

内容的提问来源于stack exchange,提问作者Paulo Junior

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 19:15:00