Comment redimensionner une Bitmap sous Android?

j'ai une image bitmap prise d'une chaîne Base64 de ma base de données distante, ( encodedImage est la chaîne représentant L'image avec 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)
);

profil is my ImageView

Ok, mais je dois redimensionner cette image avant de la montrer sur mon ImageView de ma mise en page. Je dois le redimensionner à 120x120.

quelqu'un peut-il me dire le code pour le redimensionner?

le les exemples que j'ai trouvés n'ont pas pu être appliqués à une chaîne de caractères bitmap obtenue par base64.

266
demandé sur Arslan Ali 2011-01-29 18:38:29

13 réponses

changement:

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

à:

Bitmap b = BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length)
profileImage.setImageBitmap(Bitmap.createScaledBitmap(b, 120, 120, false));
461
répondu user432209 2015-06-01 15:32:50
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;
}

EDIT: comme suggéré par @aveschini, j'ai ajouté bm.recycle(); pour les fuites de mémoire. Veuillez noter que dans le cas où vous utilisez l'objet précédent à d'autres fins, alors manipulez en conséquence.

244
répondu jeet.chanchawat 2015-08-24 10:48:30

si vous avez déjà un bitmap, vous pouvez utiliser le code suivant pour redimensionner:

Bitmap originalBitmap = <original initialization>;
Bitmap resizedBitmap = Bitmap.createScaledBitmap(
    originalBitmap, newWidth, newHeight, false);
97
répondu ZenBalance 2015-06-01 15:32:00

échelle basée sur rapport d'aspect :

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

yourSelectedImage = Bitmap.createScaledBitmap(
    yourSelectedImage, width, height, false);

pour utiliser la hauteur comme base au lieu de la largeur, remplacer par:

int height = 480;
int width = Math.round(height * aspectRatio);
32
répondu sagits 2015-06-01 15:27:34

à l'Échelle d'une image bitmap avec une cible de la taille maximale et la largeur, tout en maintenant le ratio d'aspect:

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);
21
répondu Kevin 2015-06-03 01:01:31

Quelqu'un a demandé comment garder le rapport d'aspect dans cette situation:

calculez le facteur que vous utilisez pour la mise à l'échelle et utilisez-le pour les deux dimensions. Disons que vous voulez qu'une image soit 20% de l'écran en hauteur

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

pour obtenir la résolution d'écran vous avez Cette solution: Obtenir les dimensions de l'écran en pixels

7
répondu Taochok 2017-05-23 11:47:25

essayez ce code :

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

j'espère que c'est utile.

5
répondu Ravi Makvana 2014-12-09 05:59:44

essayez ceci: Cette fonction redimensionne une bitmap proportionnellement. Lorsque le dernier paramètre est réglé sur "X" le newDimensionXorY est considéré comme la nouvelle largeur et lorsque la valeur "Y" une nouvelle hauteur.

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;
}
3
répondu user2288580 2015-06-01 15:29:51
  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 are not using mBitmap Obj
        return bitmap;
    }
3
répondu Sandy09 2016-05-10 05:58:26
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 target = Bitmap.createBitmap(width, height, getConfig(bitmap));
        Canvas canvas = new Canvas(target);
        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 target;
    }
    private static Bitmap.Config getConfig(Bitmap bitmap) {
        Bitmap.Config config = bitmap.getConfig();
        if (config == null) {
            config = Bitmap.Config.ARGB_8888;
        }
        return config;
    }
3
répondu kakopappa 2016-09-01 05:10:38
profileImage.setImageBitmap(
    Bitmap.createScaledBitmap(
        BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length), 
        80, 80, false
    )
);
2
répondu Rajkamal 2015-06-01 15:31:37

depuis API 19, Bitmap setWidth (int width) et setHeight(int height) existent. http://developer.android.com/reference/android/graphics/Bitmap.html

1
répondu afathman 2016-01-25 17:20:20

Image redimensionnée selon Toute taille d'Affichage

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 convertHighet = (int) hight, convertWidth = (int) width;

    // high length
    if (lengthbmp > hight) {
        convertHighet = (int) hight - 20;
        bitmap = Bitmap.createScaledBitmap(bitmap, convertWidth,
                convertHighet, true);
    }

    // high width
    if (widthbmp > width) {
        convertWidth = (int) width - 20;
        bitmap = Bitmap.createScaledBitmap(bitmap, convertWidth,
                convertHighet, true);
    }

    return bitmap;
}
1
répondu 2016-07-20 06:09:19