使用毕加索调整图像大小并添加到HttpPost



使用毕加索调整图像大小并使用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();

但是,据我所知,Apache HttpClient 在 Android 上已被弃用,我建议使用 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
    }
});

最新更新