How to Resize a Bitmap in Android?

后端 未结 16 1983
有刺的猬
有刺的猬 2020-11-22 03:13

I have a bitmap taken of a Base64 String from my remote database, (encodedImage is the string representing the image with Base64):

profileImage          


        
相关标签:
16条回答
  • 2020-11-22 03:45
    /**
     * Kotlin method for Bitmap scaling
     * @param bitmap the bitmap to be scaled
     * @param pixel  the target pixel size
     * @param width  the width
     * @param height the height
     * @param max    the max(height, width)
     * @return the scaled bitmap
     */
    fun scaleBitmap(bitmap:Bitmap, pixel:Float, width:Int, height:Int, max:Int):Bitmap {
        val scale = px / max
        val h = Math.round(scale * height)
        val w = Math.round(scale * width)
        return Bitmap.createScaledBitmap(bitmap, w, h, true)
      }
    
    0 讨论(0)
  • 2020-11-22 03:46

    As of API 19, Bitmap setWidth(int width) and setHeight(int height) exist. http://developer.android.com/reference/android/graphics/Bitmap.html

    0 讨论(0)
  • 2020-11-22 03:47

    Change:

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

    To:

    Bitmap b = BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length)
    profileImage.setImageBitmap(Bitmap.createScaledBitmap(b, 120, 120, false));
    
    0 讨论(0)
  • 2020-11-22 03:48
    profileImage.setImageBitmap(
        Bitmap.createScaledBitmap(
            BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length), 
            80, 80, false
        )
    );
    
    0 讨论(0)
  • 2020-11-22 03:48

    Bitmap Resize based on Any Display size

    public Bitmap bitmapResize(Bitmap imageBitmap) {
    
        Bitmap bitmap = imageBitmap;
        float heightbmp = bitmap.getHeight();
        float widthbmp = bitmap.getWidth();
    
        // Get Screen width
        DisplayMetrics displaymetrics = new DisplayMetrics();
        this.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
        float height = displaymetrics.heightPixels / 3;
        float width = displaymetrics.widthPixels / 3;
    
        int convertHeight = (int) hight, convertWidth = (int) width;
    
        // higher
        if (heightbmp > height) {
            convertHeight = (int) height - 20;
            bitmap = Bitmap.createScaledBitmap(bitmap, convertWidth,
                    convertHighet, true);
        }
    
        // wider
        if (widthbmp > width) {
            convertWidth = (int) width - 20;
            bitmap = Bitmap.createScaledBitmap(bitmap, convertWidth,
                    convertHeight, true);
        }
    
        return bitmap;
    }
    
    0 讨论(0)
  • 2020-11-22 03:52

    If you already have a bitmap, you could use the following code to resize:

    Bitmap originalBitmap = <original initialization>;
    Bitmap resizedBitmap = Bitmap.createScaledBitmap(
        originalBitmap, newWidth, newHeight, false);
    
    0 讨论(0)
提交回复
热议问题