我需要从相机获取图像,将其转换为哈希值,然后以 JSON 格式发送给提供商。
但是,当我从相机拍摄图像时,位图质量下降。拍摄图像后,在结果屏幕中图像具有正确的质量,但是,在我从结果回调的数据中检索位图后,图像失去质量:
Intent camera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
launcherForCamera.launch(camera);
launcherForCamera = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>()
{
@Override
public void onActivityResult(ActivityResult result)
{
if (result.getResultCode() == RESULT_OK)
{
Bitmap image = (Bitmap) result.getData().getExtras().get("data");
if (image != null)
{
File directoryPath = Environment.getExternalStoragePublicDirectory("/Test/Images/");
if (!directoryPath.exists())
{
directoryPath.mkdir();
}
File file = new File(directoryPath, System.currentTimeMillis() + ".jpg");
try
{
FileOutputStream outputStream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
Toast.makeText(getContext(), "Picture saved successfully", Toast.LENGTH_LONG).show();
outputStream.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
});
我尝试将 JPEG 压缩格式更改为 PNG,但没有成功。我不会保存图像,只会将其转换为哈希值。
您面临的问题可能与如何从相机意图返回图像数据有关。在您提供的代码中,您将使用“data”键检索缩略图数据。该缩略图通常是捕获图像的较低分辨率版本。
要获取全分辨率图像,您应该将其保存到您指定的文件中(您正在执行此操作),然后使用该文件的路径来操作或处理图像。这是代码的更新版本:
Intent camera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
launcherForCamera.launch(camera);
launcherForCamera = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
if (result.getResultCode() == RESULT_OK) {
Bundle extras = result.getData().getExtras();
if (extras != null && extras.get("data") != null) {
// Thumbnail image (lower resolution)
Bitmap thumbnail = (Bitmap) extras.get("data");
// Use the file you've saved
File directoryPath = Environment.getExternalStoragePublicDirectory("/Test/Images/");
if (!directoryPath.exists()) {
directoryPath.mkdirs();
}
File file = new File(directoryPath, System.currentTimeMillis() + ".jpg");
try {
FileOutputStream outputStream = new FileOutputStream(file);
thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
Toast.makeText(getContext(), "Thumbnail picture saved successfully", Toast.LENGTH_LONG).show();
outputStream.close();
// Process the full-resolution image from the file path
// You can use 'file' here to process the full image or create a hash
// Example: convertFileToHash(file);
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
在此代码中,缩略图是相机捕获的较低分辨率图像,而文件变量保存高分辨率图像的路径。您应该使用该文件执行进一步的处理,例如创建哈希,而不是使用缩略图。