使用毕加索调整图像大小并使用httppost上传图像的最佳方法是什么?

Bitmap bmp = Picasso.with(context)
                    .load(path)
                    .resize(1000, 1000)
                    .centerInside()
                    .onlyScaleDown()
                    .get();

MultipartEntity entity = new MultipartEntity();
entity.addPart("image", new FileBody(file));

最好的方法(记忆)是什么?
澄清:现在我正在做
位图b=picasso.resize().get();
创建新文件
将位图B写入文件
在httppost中包含文件
我在寻找是否有更有效的方法

最佳答案

你可以这样做:

Bitmap bmp = Picasso.with(context)
                .load(path)
                .resize(1000, 1000)
                .centerInside()
                .onlyScaleDown()
                .get();

ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);

HttpEntity entity = MultipartEntityBuilder.create()
        .addBinaryBody("image", new ByteArrayInputStream(stream.toByteArray()), ContentType.create("image/png"), "filename.png")
        .build();

但是,据我所知,在android上不推荐使用apache httpclient,我建议使用OkHttp3库来发出http请求。
例子:
Bitmap bitmap = Picasso.with(context)
            .load(path)
            .resize(1000, 1000)
            .centerInside()
            .onlyScaleDown()
            .get();

ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);

RequestBody requestBody = new MultipartBody.Builder()
        .addFormDataPart("image", "filename.png", RequestBody.create(MediaType.parse("image/png"), stream.toByteArray()))
        .build();

Request request = new Request.Builder()
        .url("https://example.com")
        .post(requestBody)
        .build();

OkHttpClient client = new OkHttpClient();

client.newCall(request).enqueue(new Callback() {
    @Override
    public void onFailure(Call call, IOException e) {
        // handle failure
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
        // handle server response
    }
});

07-24 09:38
查看更多