简体   繁体   English

在上传到服务器之前如何用Picasso调整图像大小?

[英]How to resize image with Picasso before upload to server?

I am uploading images with loopj. 我正在使用loopj上传图像。

params.put("file_"+key+"", new File(String.valueOf(value.getOriginalPath())));

but i want to resize image before upload. 但我想在上传之前调整图像大小。 Is there a way to resize image "on the fly" - without resizing->saving to SD->uploading? 有没有一种方法可以即时调整图片大小-无需调整大小->保存到SD->上载? just resize im memory and upload - InputStream? 只是调整即时消息内存大小并上传-InputStream?

Thanks. 谢谢。

You can use Bitmap s createScaledBitmap() as explained eg here 您可以按照此处的说明使用BitmapcreateScaledBitmap()

How about this one: How to Resize a Bitmap in Android? 怎么样: 如何在Android中调整位图的大小?

EDIT - Sending bitmap to server 编辑-将位图发送到服务器

A bitmap in memory is quite large as it is not compressed like a PNG or JPEG, instead for every pixel you need 3 or even 4 bytes of memory. 内存中的位图非常大,因为它没有像PNG或JPEG那样被压缩,而是每个像素需要3甚至4字节的内存。 Thus you'll want to convert that bitmap into eg an PNG before uploading. 因此,您将需要在上传之前将该位图转换为PNG。 This can be done with the Bitmap.compress(...) method, which requires an OutputStream to write the compressed image to. 这可以通过Bitmap.compress(...)方法来完成,该方法需要OutputStream来将压缩图像写入其中。 As you do not want to save the image to SD card before uploading, you can use an ByteArrayOutputStream instead to keep the compressed image in memory. 由于您不想在上传之前将图像保存到SD卡,因此可以使用ByteArrayOutputStream代替,将压缩后的图像保留在内存中。

Then, you can attach an ByteArrayInputStream to the bytes written and pass that to loopj. 然后,您可以将ByteArrayInputStream附加到写入的字节上,并将其传递给loopj。

In code this should look something like so: 在代码中,看起来应该像这样:

ByteArrayOutputStream outStream = new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.PNG, quality, outStream);
ByteArrayInputStream inStream = new ByteArrayInputStream(outStream.toByteArray());

/* ...and then pass inStream loopj */
Target mTarget = new Target() {
    @Override
    public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom loadedFrom) {
        Log.d("!!!!!",">>>>>>>>>>>>");
        SaveImage.SaveImageFromBitmap(bitmap);
    }

    @Override
    public void onBitmapFailed(Drawable drawable) {
        Log.d("!!!!!","--------");
    }

    @Override
    public void onPrepareLoad(Drawable drawable) {

    }
};
File file = new File(value.getOriginalPathString());
Picasso.with(AddSpa.this).load(file).resize(800,0).into(mTarget);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM