簡體   English   中英

調整大小並壓縮從圖庫上傳時的圖像

[英]resize and compress image on upload from gallery

我想壓縮從圖庫上傳的圖像。 我為此目的使用“ id.zelory:compressor”庫。

            case REQUEST_GALLERY_CODE: {
            if (resultCode == RESULT_OK && null != data) {
                try {
                    InputStream inputStream = getContentResolver().openInputStream(data.getData());
                    String type = getFileExtension(data.getData());
                    UploadImage(getBytes(inputStream) , type);

和getbytes函數:

    private byte[] getBytes(InputStream is) throws IOException {
    ByteArrayOutputStream byteBuff = new ByteArrayOutputStream();
    int buffSize = 1024;
    byte[] buff = new byte[buffSize];
    int len = 0;
    while ((len = is.read(buff)) != -1) {
        byteBuff.write(buff, 0, len);
    }
    return byteBuff.toByteArray();
}

我想在發送圖像上傳(UploadImage())之前使用以下方法對其進行壓縮:

compressedImageFile = new Compressor(this).compressToFile(actualImageFile);

但是輸入的這段代碼是actualImageFile! 怎么辦呢?

您可以使用本地質量更改。 在我的最新項目中,我使用了以下方法:

 val image = data?.extras?.get("data") as Bitmap
 val byteArrayOutputStream = ByteArrayOutputStream()
 image.compress(Bitmap.CompressFormat.PNG,IMAGE_QUALITY, byteArrayOutputStream)
 val byteArray = byteArrayOutputStream.toByteArray()
 service.send(Item(Base64.encodeToString(byteArray, Base64.DEFAULT))

IMAGE_QUALITY是0到100之間的數字。 您可以玩數字游戲,看看哪種質量可以滿足您的需求

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM