How to Resize a Bitmap in Android?

后端 未结 16 2397
有刺的猬
有刺的猬 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:39

    Keeping the aspect ratio,

      public Bitmap resizeBitmap(Bitmap source, int width,int height) {
        if(source.getHeight() == height && source.getWidth() == width) return source;
        int maxLength=Math.min(width,height);
        try {
            source=source.copy(source.getConfig(),true);
            if (source.getHeight() <= source.getWidth()) {
                if (source.getHeight() <= maxLength) { // if image already smaller than the required height
                    return source;
                }
    
                double aspectRatio = (double) source.getWidth() / (double) source.getHeight();
                int targetWidth = (int) (maxLength * aspectRatio);
    
                return Bitmap.createScaledBitmap(source, targetWidth, maxLength, false);
            } else {
    
                if (source.getWidth() <= maxLength) { // if image already smaller than the required height
                    return source;
                }
    
                double aspectRatio = ((double) source.getHeight()) / ((double) source.getWidth());
                int targetHeight = (int) (maxLength * aspectRatio);
    
                return Bitmap.createScaledBitmap(source, maxLength, targetHeight, false);
    
            }
        }
        catch (Exception e)
        {
            return source;
        }
    }
    

提交回复
热议问题