小尺寸图片上传

时间:2017-04-01 19:28:44

标签: android android-volley android-image android-bitmap android-file

我尝试将图片上传到服务器。我按路径获取图像并将其转换为字节数组:

BitmapFactory.Options bmOptions = new BitmapFactory.Options();
Bitmap picture = BitmapFactory.decodeFile(imagePath, bmOptions);

MultipartEntityBuilder builder = MultipartEntityBuilder.create();
ByteArrayOutputStream bao = new ByteArrayOutputStream();

bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bao);
byte[] bytes = bao.toByteArray();

builder.addPart("uploadedfile", new ByteArrayBody(bytes, "name" + ".jpg"));

例如,图片的尺寸为300kb,但上传图片的尺寸为800kb。

如何在不增加尺寸的情况下发送图像(按路径选择)?

SOULUTION

@greenapps吧。我将图像转换为文件:

public static byte[] fullyReadFileToBytes(File f) throws IOException {
    int size = (int) f.length();
    byte bytes[] = new byte[size];
    byte tmpBuff[] = new byte[size];
    FileInputStream fis= new FileInputStream(f);;
    try {

        int read = fis.read(bytes, 0, size);
        if (read < size) {
            int remain = size - read;
            while (remain > 0) {
                read = fis.read(tmpBuff, 0, remain);
                System.arraycopy(tmpBuff, 0, bytes, size - remain, read);
                remain -= read;
            }
        }
    }  catch (IOException e){
        throw e;
    } finally {
        fis.close();
    }

    return bytes;
}

1 个答案:

答案 0 :(得分:1)

将图像文件放在字节数组中,而不使用中间位图。