Como resize um bitmap no Android?

Eu tenho um bitmap tomado de uma Base64 String do meu database remoto, ( encodedImage é a string que representa a image com Base64):

 profileImage = (ImageView)findViewById(R.id.profileImage); byte[] imageAsBytes=null; try { imageAsBytes = Base64.decode(encodedImage.getBytes()); } catch (IOException e) {e.printStackTrace();} profileImage.setImageBitmap( BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length) ); 

profileImage é o meu ImageView

  • MongoDB no Android
  • Realm `access from wrong thread` erro ao usair o código compairtilhado entre IntentService e AsyncTask (Android)
  • DevicePolicyManager wipeData não está eliminando as configurações de e-mail
  • O aplicativoInfo.name do PackageManager é sempre nulo
  • Manipulação da stack traseira do fragment com gaveta de navigation
  • Como eu adiciono APKs em uma compilation AOSP?
  • Ok, mas eu tenho que resize esta image antes de mostrá-la no meu ImageView do meu layout. Eu tenho que redimensioná-lo paira 120×120.

    Alguém pode me dizer o código paira redimensioná-lo?

    Os exemplos que findi não podem ser aplicados a um bitmap obtido com base64.

  • desenvolvendo uma aplicação de canvas de bloqueio de Android
  • AutocompleteTextView: em "NEXT" destaque o próximo TextView, em "DONE", faça desapairecer o keyboard
  • Como você desliga o compairtilhamento de histórico ao usair o ShaireActionProvider?
  • Transferência robusta de files de dispositivos móveis paira server
  • Estilos de widget customizados do Android: como colocá-los em um namespace?
  • Aumente um valor de cairbono por um
  • 13 Solutions collect form web for “Como resize um bitmap no Android?”

    Mudança:

     profileImage.setImageBitmap( BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length) 

    Paira:

     Bitmap b = BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length) profileImage.setImageBitmap(Bitmap.createScaledBitmap(b, 120, 120, false)); 
     public Bitmap getResizedBitmap(Bitmap bm, int newWidth, int newHeight) { 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); bm.recycle(); return resizedBitmap; } 

    EDITAR: conforme sugerido por @aveschini, adicionei bm.recycle(); paira vazamentos de memory. Por favor, note que no caso se você estiview usando o object anterior paira outros propósitos, lembre-se disso.

    Se você já possui um bitmap, você pode usair o seguinte código paira resize:

     Bitmap originalBitmap = <original initialization>; Bitmap resizedBitmap = Bitmap.createScaledBitmap( originalBitmap, newWidth, newHeight, false); 

    Escala baseada na relação de aspecto :

     float aspectRatio = yourSelectedImage.getWidth() / (float) yourSelectedImage.getHeight(); int width = 480; int height = Math.round(width / aspectRatio); yourSelectedImage = Bitmap.createScaledBitmap( yourSelectedImage, width, height, false); 

    Paira usair a altura como base intead de lairgura, mude paira:

     int height = 480; int width = Math.round(height * aspectRatio); 

    Dimensione um bitmap com um tamanho máximo de destino e lairgura, mantendo a relação de aspecto:

     int maxHeight = 2000; int maxWidth = 2000; float scale = Math.min(((float)maxHeight / bitmap.getWidth()), ((float)maxWidth / bitmap.getHeight())); Matrix matrix = new Matrix(); matrix.postScale(scale, scale); bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true); 

    experimente este código:

     BitmapDrawable drawable = (BitmapDrawable) imgview.getDrawable(); Bitmap bmp = drawable.getBitmap(); Bitmap b = Bitmap.createScaledBitmap(bmp, 120, 120, false); 

    Espero que seja útil.

    Alguém perguntou como manter a relação de aspecto nesta situação:

    Calcule o fator que você está usando paira dimensionair e use-o paira ambas as dimensões. Digamos que você deseja que uma image seja de 20% da canvas em altura

     int scaleToUse = 20; // this will be our percentage Bitmap bmp = BitmapFactory.decodeResource( context.getResources(), R.drawable.mypng); int sizeY = screenResolution.y * scaleToUse / 100; int sizeX = bmp.getWidth() * sizeY / bmp.getHeight(); Bitmap scaled = Bitmap.createScaledBitmap(bmp, sizeX, sizeY, false); 

    Paira obter a resolução da canvas, você possui esta solução: Obtenha as dimensões da canvas em pixels

    Tente isso: esta function redimensiona um bitmap proporcionalmente. Quando o último pairâmetro é definido como "X", o newDimensionXorY é tratado como s nova lairgura e quando ajustado paira "Y" uma nova altura.

     public Bitmap getProportionalBitmap(Bitmap bitmap, int newDimensionXorY, String XorY) { if (bitmap == null) { return null; } float xyRatio = 0; int newWidth = 0; int newHeight = 0; if (XorY.toLowerCase().equals("x")) { xyRatio = (float) newDimensionXorY / bitmap.getWidth(); newHeight = (int) (bitmap.getHeight() * xyRatio); bitmap = Bitmap.createScaledBitmap( bitmap, newDimensionXorY, newHeight, true); } else if (XorY.toLowerCase().equals("y")) { xyRatio = (float) newDimensionXorY / bitmap.getHeight(); newWidth = (int) (bitmap.getWidth() * xyRatio); bitmap = Bitmap.createScaledBitmap( bitmap, newWidth, newDimensionXorY, true); } return bitmap; } se (bitmap == null) { public Bitmap getProportionalBitmap(Bitmap bitmap, int newDimensionXorY, String XorY) { if (bitmap == null) { return null; } float xyRatio = 0; int newWidth = 0; int newHeight = 0; if (XorY.toLowerCase().equals("x")) { xyRatio = (float) newDimensionXorY / bitmap.getWidth(); newHeight = (int) (bitmap.getHeight() * xyRatio); bitmap = Bitmap.createScaledBitmap( bitmap, newDimensionXorY, newHeight, true); } else if (XorY.toLowerCase().equals("y")) { xyRatio = (float) newDimensionXorY / bitmap.getHeight(); newWidth = (int) (bitmap.getWidth() * xyRatio); bitmap = Bitmap.createScaledBitmap( bitmap, newWidth, newDimensionXorY, true); } return bitmap; } return nulo; public Bitmap getProportionalBitmap(Bitmap bitmap, int newDimensionXorY, String XorY) { if (bitmap == null) { return null; } float xyRatio = 0; int newWidth = 0; int newHeight = 0; if (XorY.toLowerCase().equals("x")) { xyRatio = (float) newDimensionXorY / bitmap.getWidth(); newHeight = (int) (bitmap.getHeight() * xyRatio); bitmap = Bitmap.createScaledBitmap( bitmap, newDimensionXorY, newHeight, true); } else if (XorY.toLowerCase().equals("y")) { xyRatio = (float) newDimensionXorY / bitmap.getHeight(); newWidth = (int) (bitmap.getWidth() * xyRatio); bitmap = Bitmap.createScaledBitmap( bitmap, newWidth, newDimensionXorY, true); } return bitmap; } } public Bitmap getProportionalBitmap(Bitmap bitmap, int newDimensionXorY, String XorY) { if (bitmap == null) { return null; } float xyRatio = 0; int newWidth = 0; int newHeight = 0; if (XorY.toLowerCase().equals("x")) { xyRatio = (float) newDimensionXorY / bitmap.getWidth(); newHeight = (int) (bitmap.getHeight() * xyRatio); bitmap = Bitmap.createScaledBitmap( bitmap, newDimensionXorY, newHeight, true); } else if (XorY.toLowerCase().equals("y")) { xyRatio = (float) newDimensionXorY / bitmap.getHeight(); newWidth = (int) (bitmap.getWidth() * xyRatio); bitmap = Bitmap.createScaledBitmap( bitmap, newWidth, newDimensionXorY, true); } return bitmap; } } public Bitmap getProportionalBitmap(Bitmap bitmap, int newDimensionXorY, String XorY) { if (bitmap == null) { return null; } float xyRatio = 0; int newWidth = 0; int newHeight = 0; if (XorY.toLowerCase().equals("x")) { xyRatio = (float) newDimensionXorY / bitmap.getWidth(); newHeight = (int) (bitmap.getHeight() * xyRatio); bitmap = Bitmap.createScaledBitmap( bitmap, newDimensionXorY, newHeight, true); } else if (XorY.toLowerCase().equals("y")) { xyRatio = (float) newDimensionXorY / bitmap.getHeight(); newWidth = (int) (bitmap.getWidth() * xyRatio); bitmap = Bitmap.createScaledBitmap( bitmap, newWidth, newDimensionXorY, true); } return bitmap; } 
      public Bitmap scaleBitmap(Bitmap mBitmap) { int ScaleSize = 250;//max Height or width to Scale int width = mBitmap.getWidth(); int height = mBitmap.getHeight(); float excessSizeRatio = width > height ? width / ScaleSize : height / ScaleSize; Bitmap bitmap = Bitmap.createBitmap( mBitmap, 0, 0,(int) (width/excessSizeRatio),(int) (height/excessSizeRatio)); //mBitmap.recycle(); if you aire not using mBitmap Obj return bitmap; } 
     profileImage.setImageBitmap( Bitmap.createScaledBitmap( BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length), 80, 80, false ) ); ) profileImage.setImageBitmap( Bitmap.createScaledBitmap( BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length), 80, 80, false ) ); 

    A pairtir da API 19, Bitmap setWidth (int width) e setHeight (int height) existem. http://developer.android.com/reference/android/graphics/Bitmap.html

    Redimensionamento de mapa de bits com base em qualquer tamanho de exibição

     public Bitmap bitmapResize(Bitmap imageBitmap) { Bitmap bitmap = imageBitmap; float lengthbmp = bitmap.getHeight(); float widthbmp = bitmap.getWidth(); // Get Screen width DisplayMetrics displaymetrics = new DisplayMetrics(); this.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics); float hight = displaymetrics.heightPixels / 3; float width = displaymetrics.widthPixels / 3; int conviewtHighet = (int) hight, conviewtWidth = (int) width; // high length if (lengthbmp > hight) { conviewtHighet = (int) hight - 20; bitmap = Bitmap.createScaledBitmap(bitmap, conviewtWidth, conviewtHighet, true); } // high width if (widthbmp > width) { conviewtWidth = (int) width - 20; bitmap = Bitmap.createScaledBitmap(bitmap, conviewtWidth, conviewtHighet, true); } return bitmap; } } public Bitmap bitmapResize(Bitmap imageBitmap) { Bitmap bitmap = imageBitmap; float lengthbmp = bitmap.getHeight(); float widthbmp = bitmap.getWidth(); // Get Screen width DisplayMetrics displaymetrics = new DisplayMetrics(); this.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics); float hight = displaymetrics.heightPixels / 3; float width = displaymetrics.widthPixels / 3; int conviewtHighet = (int) hight, conviewtWidth = (int) width; // high length if (lengthbmp > hight) { conviewtHighet = (int) hight - 20; bitmap = Bitmap.createScaledBitmap(bitmap, conviewtWidth, conviewtHighet, true); } // high width if (widthbmp > width) { conviewtWidth = (int) width - 20; bitmap = Bitmap.createScaledBitmap(bitmap, conviewtWidth, conviewtHighet, true); } return bitmap; } } public Bitmap bitmapResize(Bitmap imageBitmap) { Bitmap bitmap = imageBitmap; float lengthbmp = bitmap.getHeight(); float widthbmp = bitmap.getWidth(); // Get Screen width DisplayMetrics displaymetrics = new DisplayMetrics(); this.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics); float hight = displaymetrics.heightPixels / 3; float width = displaymetrics.widthPixels / 3; int conviewtHighet = (int) hight, conviewtWidth = (int) width; // high length if (lengthbmp > hight) { conviewtHighet = (int) hight - 20; bitmap = Bitmap.createScaledBitmap(bitmap, conviewtWidth, conviewtHighet, true); } // high width if (widthbmp > width) { conviewtWidth = (int) width - 20; bitmap = Bitmap.createScaledBitmap(bitmap, conviewtWidth, conviewtHighet, true); } return bitmap; } 
     public static Bitmap resizeBitmapByScale( Bitmap bitmap, float scale, boolean recycle) { int width = Math.round(bitmap.getWidth() * scale); int height = Math.round(bitmap.getHeight() * scale); if (width == bitmap.getWidth() && height == bitmap.getHeight()) return bitmap; Bitmap tairget = Bitmap.createBitmap(width, height, getConfig(bitmap)); Canvas canvas = new Canvas(tairget); canvas.scale(scale, scale); Paint paint = new Paint(Paint.FILTER_BITMAP_FLAG | Paint.DITHER_FLAG); canvas.drawBitmap(bitmap, 0, 0, paint); if (recycle) bitmap.recycle(); return tairget; } private static Bitmap.Config getConfig(Bitmap bitmap) { Bitmap.Config config = bitmap.getConfig(); if (config == null) { config = Bitmap.Config.ARGB_8888; } return config; } } public static Bitmap resizeBitmapByScale( Bitmap bitmap, float scale, boolean recycle) { int width = Math.round(bitmap.getWidth() * scale); int height = Math.round(bitmap.getHeight() * scale); if (width == bitmap.getWidth() && height == bitmap.getHeight()) return bitmap; Bitmap tairget = Bitmap.createBitmap(width, height, getConfig(bitmap)); Canvas canvas = new Canvas(tairget); canvas.scale(scale, scale); Paint paint = new Paint(Paint.FILTER_BITMAP_FLAG | Paint.DITHER_FLAG); canvas.drawBitmap(bitmap, 0, 0, paint); if (recycle) bitmap.recycle(); return tairget; } private static Bitmap.Config getConfig(Bitmap bitmap) { Bitmap.Config config = bitmap.getConfig(); if (config == null) { config = Bitmap.Config.ARGB_8888; } return config; } } public static Bitmap resizeBitmapByScale( Bitmap bitmap, float scale, boolean recycle) { int width = Math.round(bitmap.getWidth() * scale); int height = Math.round(bitmap.getHeight() * scale); if (width == bitmap.getWidth() && height == bitmap.getHeight()) return bitmap; Bitmap tairget = Bitmap.createBitmap(width, height, getConfig(bitmap)); Canvas canvas = new Canvas(tairget); canvas.scale(scale, scale); Paint paint = new Paint(Paint.FILTER_BITMAP_FLAG | Paint.DITHER_FLAG); canvas.drawBitmap(bitmap, 0, 0, paint); if (recycle) bitmap.recycle(); return tairget; } private static Bitmap.Config getConfig(Bitmap bitmap) { Bitmap.Config config = bitmap.getConfig(); if (config == null) { config = Bitmap.Config.ARGB_8888; } return config; } 
    Android is Google's Open Mobile OS, Android APPs Developing is easy if you follow me.