Android - Reduzieren Sie die Größe der Bilddatei

Ich habe ein URI-image-Datei, und ich möchte, um seine Größe zu reduzieren, um es hochzuladen. Anfängliche Größe der image-Datei hängt von mobile-to-mobile (2MB wie 500KB sein), aber ich möchte der endgültigen Größe auf etwa 200KB, so dass ich es hochladen.
Von was ich gelesen habe, habe ich (mindestens) 2 Möglichkeiten:

  • Mit BitmapFactory.Optionen.inSampleSizeSubsampling original-Bild und erhalten Sie ein kleineres Bild;
  • Mit Bitmap.komprimieren um das Bild zu komprimieren festlegen der Kompressionsqualität.

Was ist die beste Wahl?


Dachte ich zunächst resize-image-Breite/- Höhe bis Höhe oder Breite über 1000px (sowas wie 1024 x 768 oder andere), dann komprimieren Bild mit der abnehmenden Qualität, bis die Datei-Größe ist über 200KB. Hier ist ein Beispiel:

int MAX_IMAGE_SIZE = 200 * 1024; //max final file size
Bitmap bmpPic = BitmapFactory.decodeFile(fileUri.getPath());
if ((bmpPic.getWidth() >= 1024) && (bmpPic.getHeight() >= 1024)) {
    BitmapFactory.Options bmpOptions = new BitmapFactory.Options();
    bmpOptions.inSampleSize = 1;
    while ((bmpPic.getWidth() >= 1024) && (bmpPic.getHeight() >= 1024)) {
        bmpOptions.inSampleSize++;
        bmpPic = BitmapFactory.decodeFile(fileUri.getPath(), bmpOptions);
    }
    Log.d(TAG, "Resize: " + bmpOptions.inSampleSize);
}
int compressQuality = 104; //quality decreasing by 5 every loop. (start from 99)
int streamLength = MAX_IMAGE_SIZE;
while (streamLength >= MAX_IMAGE_SIZE) {
    ByteArrayOutputStream bmpStream = new ByteArrayOutputStream();
    compressQuality -= 5;
    Log.d(TAG, "Quality: " + compressQuality);
    bmpPic.compress(Bitmap.CompressFormat.JPEG, compressQuality, bmpStream);
    byte[] bmpPicByteArray = bmpStream.toByteArray();
    streamLength = bmpPicByteArray.length;
    Log.d(TAG, "Size: " + streamLength);
}
try {
    FileOutputStream bmpFile = new FileOutputStream(finalPath);
    bmpPic.compress(Bitmap.CompressFormat.JPEG, compressQuality, bmpFile);
    bmpFile.flush();
    bmpFile.close();
} catch (Exception e) {
    Log.e(TAG, "Error on saving file");
}

Gibt es einen besseren Weg, es zu tun? Sollte ich versuchen zu halten über alle 2-Methoden oder nur eine? Dank

InformationsquelleAutor der Frage KitKat | 2012-06-16

Schreibe einen Kommentar