如何在Android中压缩图像文件?
如何在Android中压缩图像文件?
对于每个图像,我都有其路径(以字符串形式)。然后,我将该路径字符串转换为文件。然后将该文件存储到Firebase存储中,但我的问题是查询时文件太大。因此,我需要在上传到Firebase存储之前对其进行压缩。我正在寻找方法,但始终没有找到明确的解决方案。请如果有人能够帮助我提供非常清晰和简单的解决方案,那将是非常好的。下面是我的代码。\n
for (String path: images) { try { InputStream stream = new FileInputStream(new File(path)); UploadTask uploadTask = imageStorage.putStream(stream); uploadTask.addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception exception) { // 处理上传失败的情况 Log.d("myStorage","失败 :("); } }).addOnSuccessListener(new OnSuccessListener() { @Override public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { // taskSnapshot.getMetadata() 包含文件的元数据,例如大小、内容类型和下载URL。 UrI downloadUrl = taskSnapshot.getDownloadUrl(); Log.d("myStorage","成功!"); } }); } catch (FileNotFoundException e) { e.printStackTrace(); } countDB++; }
Android中压缩图像文件的方法
在Android中,我们经常需要压缩图像文件以减小文件大小。这可以通过以下代码实现:
public static Bitmap decodeSampledBitmapFromArray(byte[] data, int reqWidth, int reqHeight) { final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeByteArray(data, 0, data.length, options); options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); options.inJustDecodeBounds = false; return BitmapFactory.decodeByteArray(data, 0, data.length, options); } public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) { final int height = options.outHeight; final int width = options.outWidth; int inSampleSize = 1; if (height > reqHeight || width > reqWidth) { final int halfHeight = height / 2; final int halfWidth = width / 2; while ((halfHeight / inSampleSize) >= reqHeight && (halfWidth / inSampleSize) >= reqWidth) { inSampleSize *= 2; } } return inSampleSize; }
通过调用`decodeSampledBitmapFromArray`方法,传入图像的字节数组和所需的宽度和高度,我们可以获得所需大小的位图。以下是将位图转换为字节数组的方法:
Bitmap bmp = Your_bitmap; ByteArrayOutputStream stream = new ByteArrayOutputStream(); bmp.compress(Bitmap.CompressFormat.PNG, 100, stream); byte[] byteArray = stream.toByteArray();
使用这些方法,我们可以方便地压缩Android中的图像文件。
问题原因:用户想要在Android中压缩图像文件,以减小文件大小。
解决方法:用户可以按照以下步骤进行操作:
1. 首先,将图像转换为位图(bitmap)格式。
2. 使用以下代码将图像转换为位图:
Bitmap bitmap = ((BitmapDrawable) logo.getDrawable()).getBitmap();
其中,将'logo'替换为相应的imageView。
3. 接着,使用以下代码将位图压缩为字节数组:
byte[] byteImage = encodeToBase64(bitmap); public static byte[] encodeToBase64(Bitmap image) { ByteArrayOutputStream byteArrayOS = new ByteArrayOutputStream(); image.compress(Bitmap.CompressFormat.PNG, 25, byteArrayOS); byte[] byteArray = byteArrayOS.toByteArray(); return byteArray; }
这段代码将位图压缩为PNG格式,压缩比例为25%。将图像存储为字节数组,并存储在'byteImage'变量中。
4. 如果用户想要将图像大小固定为1024 x 1024像素,可以尝试使用TinyPNG API,通过以下链接访问:TinyPNG。
如何在Android中压缩图像文件?
在Firebase存储中,我有一个用于图像压缩的自定义类,可以大大减小文件的大小。该类可用于在发送到Firebase之前压缩位图和文件。
以下是用于图像压缩的自定义类的代码:
public class ImageCompression { public static Bitmap getThumbnail(Uri uri, Context context) throws FileNotFoundException, IOException { InputStream input = context.getContentResolver().openInputStream(uri); BitmapFactory.Options onlyBoundsOptions = new BitmapFactory.Options(); onlyBoundsOptions.inJustDecodeBounds = true; onlyBoundsOptions.inDither = true;//optional onlyBoundsOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;//optional BitmapFactory.decodeStream(input, null, onlyBoundsOptions); input.close(); if ((onlyBoundsOptions.outWidth == -1) || (onlyBoundsOptions.outHeight == -1)) return null; int originalSize = (onlyBoundsOptions.outHeight > onlyBoundsOptions.outWidth) ? onlyBoundsOptions.outHeight : onlyBoundsOptions.outWidth; double ratio = (originalSize > 500) ? (originalSize / 500) : 1.0; BitmapFactory.Options bitmapOptions = new BitmapFactory.Options(); bitmapOptions.inSampleSize = getPowerOfTwoForSampleRatio(ratio); bitmapOptions.inDither = true;//optional bitmapOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;//optional input = context.getContentResolver().openInputStream(uri); Bitmap bitmap = BitmapFactory.decodeStream(input, null, bitmapOptions); input.close(); return bitmap; } private static int getPowerOfTwoForSampleRatio(double ratio) { int k = Integer.highestOneBit((int) Math.floor(ratio)); if (k == 0) return 1; else return k; } public static File compressFile(File file, Context context) { try { BitmapFactory.Options o = new BitmapFactory.Options(); o.inJustDecodeBounds = true; o.inSampleSize = 6; FileInputStream inputStream = new FileInputStream(file); BitmapFactory.decodeStream(inputStream, null, o); inputStream.close(); final int REQUIRED_SIZE = 75; int scale = 1; while (o.outWidth / scale / 2 >= REQUIRED_SIZE && o.outHeight / scale / 2 >= REQUIRED_SIZE) { scale *= 2; } BitmapFactory.Options o2 = new BitmapFactory.Options(); o2.inSampleSize = scale; inputStream = new FileInputStream(file); Bitmap selectedBitmap = BitmapFactory.decodeStream(inputStream, null, o2); inputStream.close(); file.createNewFile(); FileOutputStream outputStream = new FileOutputStream(file); selectedBitmap.compress(Bitmap.CompressFormat.JPEG, 50, outputStream); return file; } catch (Exception e) { return null; } } } ImageCompression.compressFile(YourFile, this); ImageCompression.getThumbnail(YourUri, this);
以上是一个用于在Android中压缩图像文件的自定义类。您可以使用`compressFile`方法来压缩文件,使用`getThumbnail`方法来获取缩略图。
在上述代码中,有一些关于上下文(Context)的问题。在这种情况下,可以使用应用程序的上下文(Application Context)。
希望这个详细的解决方案对您有所帮助!