Upload compressed image

后端 未结 3 578
旧时难觅i
旧时难觅i 2021-01-03 18:52

I am new to android. I have created one app to upload an image to server. It works perfectly for small size images but for larger images(>1 MB), this does not work. Here is

3条回答
  •  南笙
    南笙 (楼主)
    2021-01-03 19:24

    You need to do this man:

    1: Get Image and check size. For example: if fileSize<=1MB

    2: ShrinkBitmap (So that large image won't cause memory issues. See ShrinkBitmap() below.

    3: If you want to Encode to base64 or else then you can do it and compress to 100%. See Encodetobase64() below

    4: Send to Server

    public Bitmap ShrinkBitmap(String file, int width, int height)
    {
        BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
        bmpFactoryOptions.inJustDecodeBounds = true;
        Bitmap bitmap = BitmapFactory.decodeFile(file, bmpFactoryOptions);
    
        int heightRatio = (int) Math.ceil(bmpFactoryOptions.outHeight / (float) height);
        int widthRatio = (int) Math.ceil(bmpFactoryOptions.outWidth / (float) width);
    
        if(heightRatio > 1 || widthRatio > 1)
        {
            if(heightRatio > widthRatio)
            {
                bmpFactoryOptions.inSampleSize = heightRatio;
            }
            else
            {
                bmpFactoryOptions.inSampleSize = widthRatio;
            }
        }
    
        bmpFactoryOptions.inJustDecodeBounds = false;
        bitmap = BitmapFactory.decodeFile(file, bmpFactoryOptions);
        return bitmap;
    }  
    
    
    
        public String encodeTobase64(Bitmap image)
    {
        String byteImage = null;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        byte[] b = baos.toByteArray();
        try
        {
            System.gc();
            byteImage = Base64.encodeToString(b, Base64.DEFAULT);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        catch (OutOfMemoryError e)
        {
            baos = new ByteArrayOutputStream();
            image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
            b = baos.toByteArray();
            byteImage = Base64.encodeToString(b, Base64.DEFAULT);
            Log.e("Bitmap", "Out of memory error catched");
        }
        return byteImage;
    }  
    

    This encoding function is compressing bitmap also.

    Goodluck!!

提交回复
热议问题