2017-11-20 2 views
0

Ich habe eine Funktion, um Bild in Array-Byte zu konvertieren (um Bild in Datenbank sqlite zu speichern). Ich habe ein Problem, wie Bild zu komprimieren und Fehler wegen zu wenig Arbeitsspeichers zu vermeiden? Das ist mein Code Vielen Dank im Voraus.Bild in Bitmap konvertieren und komprimieren

public byte[] ConverttoArrayByte(ImageView img) 
{ 
    try{ 
     BitmapDrawable bitmapDrawable = (BitmapDrawable) img.getDrawable(); 
     Bitmap bitmap = bitmapDrawable.getBitmap(); 
     ByteArrayOutputStream stream = new ByteArrayOutputStream(); 
     bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream); 
     return stream.toByteArray(); 
    }catch (NullPointerException e){ 
     Log.d("Tag", "Null"); 
     e.printStackTrace(); 
    } 
    return null; 
} 

Antwort

0

können Sie versuchen, eine kleine Funktion zu verwenden, die das Bild passt die Größe:

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); 
    } 

Und rufen Sie diese Funktion auf diese Weise Bitmap bitmap = GetAttachmentsUtils.getResizedBitmap(bitmap, maxSize); das verkleinerte Bitmap zu erhalten.

Dann können Sie es mit bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream); komprimieren und die gleichen Operationen ausführen, die Sie zuvor getan haben.

Verwandte Themen