android - 如何获取画廊图像的压缩图像uri?
问题描述
我正在处理需要压缩图像并且需要为该压缩图像获取 Uri 的项目。问题是当我尝试从图库中压缩图像时,它正在创建另外一张图像,该图像与具有不同分辨率的原始图像一起压缩如何实现,就像我应该在图库中只有一个图像参考,这也是原始图像而不是压缩图像. 请在下面找到我尝试过的代码片段
public static Bitmap getResizedBitmap(Bitmap image, int maxSize) {
int width = image.getWidth();
int height = image.getHeight();
float bitmapRatio = (float) width / (float) height;
if (bitmapRatio > 1) {
width = maxSize;
height = (int) (width / bitmapRatio);
} else {
height = maxSize;
width = (int) (height * bitmapRatio);
}
return Bitmap.createScaledBitmap(image, width, height, true);
}
private static Bitmap rotateImage(Bitmap img, float degree) {
Matrix matrix = new Matrix();
matrix.postRotate(degree);
Bitmap rotatedImg = Bitmap.createBitmap(img, 0, 0, img.getWidth(), img.getHeight(), matrix, true);
//img.recycle();
return rotatedImg;
}
private static Bitmap rotateImageIfRequired(Context context, Bitmap img, Uri selectedImage) throws IOException {
InputStream input = context.getContentResolver().openInputStream(selectedImage);
ExifInterface ei;
if (Build.VERSION.SDK_INT > 23)
ei = new ExifInterface(input);
else
ei = new ExifInterface(selectedImage.getPath());
int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
return rotateImage(img, 90);
case ExifInterface.ORIENTATION_ROTATE_180:
return rotateImage(img, 180);
case ExifInterface.ORIENTATION_ROTATE_270:
return rotateImage(img, 270);
default:
return img;
}
}
public static Uri compressedImageUri(Uri selectedImage, Context context) {
try {
InputStream imageStream = null;
try {
imageStream = context.getContentResolver().openInputStream(
selectedImage);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Bitmap original = BitmapFactory.decodeStream(imageStream);
//Bitmap bmp = getResizedBitmap(original, 500);
Bitmap rotateBitmap = rotateImageIfRequired(context, original, selectedImage);
Bitmap bmp = getResizedBitmap(rotateBitmap, 500);
String path = MediaStore.Images.Media.insertImage(context.getContentResolver(), bmp, String.valueOf(System.currentTimeMillis()), null);
return Uri.parse(path);
} catch (Exception e) {
Log.d("error", e.getLocalizedMessage());
}
return null;
}
解决方案
File imgFile = new File(uri.getPath());
File compressFile = Compressor.getDefault(getContext()).compressToFile(imgFile);
您可能需要其他课程,因此请检查compressor
包。希望这会帮助你。
推荐阅读
- c - 使用 SGX 的 C 语言中的 Hello World
- html - 如何使省略号出现在文本中
- google-apps-script - 通过 API 更改图表字体名称时出现内部服务器错误
- python - Maya – 如何使用 Python 自动化设置驱动键?
- python - 使用 PyTCC 库从 C 函数返回 PyObject 时如何修复“访问冲突”错误
- javascript - 根据对象中的另一个变量对空值进行排序
- python - 为什么我可以打印这个列表列表,但只追加所有内容,不包括每次迭代的最后一个元素?
- swift - NSTextView 不支持 Cocoa 应用程序中的重做和撤消
- makefile - 调用shell写入makefile中的文件
- objective-c - 为什么我的 AUv3 随“viewServiceDidTerminateWithError”随机消失?