2011-12-07 17 views
9

Estoy cargando una imagen a un servidor y, antes de que eso ocurra, me gustaría cambiar el tamaño de las dimensiones de la imagen. Me da la imagen con un URI así:cambiar el tamaño de la imagen del archivo

Constants.currImageURI = data.getData(); 

Este es el llamado a subir la imagen:

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

¿Hay una manera de cambiar el tamaño del archivo en función de las dimensiones en píxeles?

Gracias.

Respuesta

8

Esto está tomado de ThinkAndroid en la siguiente dirección: http://thinkandroid.wordpress.com/2009/12/25/resizing-a-bitmap/

Me gustaría ver en la posibilidad de crear un mapa de bits o Disponibles a partir del recurso y si desea cambiar su tamaño utilizar el código de abajo.

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: Como se sugiere en otro comentario Bitmap.createScaledBitmap se debe utilizar para una mejor calidad al cambiar el tamaño.

21

Uso Bitmap.createScaledBitmap como se sugiere otros.

Sin embargo, esta función no es muy inteligente. Si va a escalar a menos del 50% del tamaño, es muy probable que conseguir esto:

enter image description here

lugar de esto:

enter image description here

¿Usted ve mal antialiasing de primera imagen ? createScaledBitmap obtendrá este resultado.

El motivo es el filtrado de píxeles, donde algunos píxeles se saltan por completo de la fuente si se escalan a < 50%.

Para obtener el resultado de la 2ª calidad, debe reducir a la mitad la resolución del mapa de bits si es más de 2 veces mayor que el resultado deseado, y finalmente realizar una llamada para crear el mapa escalar.

Y hay más enfoques para reducir a la mitad (o un cuarto, o aumentar) las imágenes. Si tiene Bitmap en la memoria, recursivamente llama a Bitmap.createScaledBitmap para dividir la imagen a la mitad.

Si carga imágenes del archivo JPG, la implementación es aún más rápida: usa BitmapFactory.decodeFile y el parámetro Opciones de configuración correctamente, principalmente el campo inSampleSize, que controla el subuncionamiento de imágenes cargadas, utilizando las características de JPEG.

Muchas aplicaciones que proporcionan miniaturas de imágenes utilizan a ciegas Bitmap.createScaledBitmap, y las miniaturas son simplemente feas. Sea inteligente y use una resolución de imagen adecuada.

3

Vea lo que 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; 
} 

que llame a la anterior para cambiar el tamaño de una imagen grande:

// 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()); 
} 
Cuestiones relacionadas