2011-12-07 15 views
9

Sto caricando un'immagine su un server e prima che ciò accada, vorrei ridimensionare le dimensioni dell'immagine. Ho l'immagine con un URI come questo:ridimensiona immagine da file

Constants.currImageURI = data.getData(); 

Questa è la chiamata per caricare l'immagine:

String response = uploadUserPhoto(new File(getRealPathFromURI(Constants.currImageURI))); 

    public String uploadUserPhoto(File image) { 

    DefaultHttpClient mHttpClient; 
    HttpParams params = new BasicHttpParams(); 
    params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); 
    mHttpClient = new DefaultHttpClient(params); 

    try { 
     HttpPost httppost = new HttpPost("http://myurl/mobile/image"); 

     MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); 
     multipartEntity.addPart("userID", new StringBody(Constants.userID)); 
     multipartEntity.addPart("uniqueMobileID", new StringBody(Constants.uniqueMobileID)); 
     multipartEntity.addPart("userfile", new FileBody(image, "mobileimage.jpg", "image/jpeg", "UTF-8")); 
     httppost.setEntity(multipartEntity); 

     HttpResponse response = mHttpClient.execute(httppost); 
     String responseBody = EntityUtils.toString(response.getEntity()); 

     Log.d(TAG, "response: " + responseBody); 
     return responseBody; 

    } catch (Exception e) { 
     Log.d(TAG, e.getMessage()); 
    } 
    return ""; 
} 

Esiste un modo per ridimensionare il file in base a dimensioni in pixel?

Grazie.

risposta

8

Questo è preso da ThinkAndroid a questo indirizzo: http://thinkandroid.wordpress.com/2009/12/25/resizing-a-bitmap/

vorrei esaminare la possibilità di creare una bitmap o Drawable dalla risorsa e se si vuole cambiare la sua dimensione utilizzare il codice qui sotto.

public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) { 
    int width = bm.getWidth(); 
    int height = bm.getHeight(); 
    float scaleWidth = ((float) newWidth)/width; 
    float scaleHeight = ((float) newHeight)/height; 

    // Create a matrix for the manipulation 
    Matrix matrix = new Matrix(); 

    // Resize the bit map 
    matrix.postScale(scaleWidth, scaleHeight); 

    // Recreate the new Bitmap 
    Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false); 
    return resizedBitmap; 

} 

EDIT: Come suggerito in altro commento Bitmap.createScaledBitmap dovrebbe essere utilizzato per una migliore qualità quando si ridimensiona.

21

Usa Bitmap.createScaledBitmap come gli altri suggerito.

Tuttavia, questa funzione non è molto intelligente. Se stai scala a misura inferiore al 50%, è probabile che per ottenere questo:

enter image description here

Invece di questo:

enter image description here

Non si vede male antialiasing di prima immagine ? createScaledBitmap ti farà ottenere questo risultato.

Il motivo è il filtraggio dei pixel, in cui alcuni pixel vengono completamente ignorati dalla sorgente se si ridimensiona a < 50%.

Per ottenere il risultato di 2a qualità, è necessario dimezzare la risoluzione di Bitmap se è maggiore di 2 volte rispetto al risultato desiderato, quindi si effettua la chiamata a createScaledBitmap.

E ci sono più approcci per dimezzare (o un quarto, o otto) immagini. Se si dispone di Bitmap in memoria, si chiama ricorsivamente Bitmap.createScaledBitmap per dimezzare l'immagine.

Se si carica un'immagine da file JPG, l'attuazione è ancora più veloce: si utilizza BitmapFactory.decodeFile e opzioni di impostazione dei parametri correttamente, campo principalmente inSampleSize, che controlla subsambling di immagini caricate, utilizzando le caratteristiche di JPEG.

Molte app che forniscono miniature di immagini utilizzano Bitmap.createScaledBitmap alla cieca, e le miniature sono semplicemente brutte. Sii furbo e usa il downsampling corretto dell'immagine.

3

Vedere che cosa Google recommends doing (as @Pointer Null advised):

public int calculateInSampleSize(
      BitmapFactory.Options options, int reqWidth, int reqHeight) { 
    // Raw height and width of image 
    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; 

     // Calculate the largest inSampleSize value that is a power of 2 and keeps both 
     // height and width larger than the requested height and width. 
     while ((halfHeight/inSampleSize) > reqHeight 
       && (halfWidth/inSampleSize) > reqWidth) { 
      inSampleSize *= 2; 
     } 
    } 

    return inSampleSize; 
} 

chiamo il sopra per ridimensionare un'immagine di grandi dimensioni:

// Check if source and destination exist 
// Check if we have read/write permissions 

int desired_width = 200; 
int desired_height = 200; 

BitmapFactory.Options options = new BitmapFactory.Options(); 
options.inJustDecodeBounds = true; 

BitmapFactory.decodeFile(SOME_PATH_TO_LARGE_IMAGE, options); 

options.inSampleSize = calculateInSampleSize(options, desired_width, desired_height); 
options.inJustDecodeBounds = false; 

Bitmap smaller_bm = BitmapFactory.decodeFile(src_path, options); 

FileOutputStream fOut; 
try { 
    File small_picture = new File(SOME_PATH_STRING); 
    fOut = new FileOutputStream(small_picture); 
    // 0 = small/low quality, 100 = large/high quality 
    smaller_bm.compress(Bitmap.CompressFormat.JPEG, 50, fOut); 
    fOut.flush(); 
    fOut.close(); 
    smaller_bm.recycle(); 
} catch (Exception e) { 
    Log.e(LOG_TAG, "Failed to save/resize image due to: " + e.toString()); 
} 
Problemi correlati