Glide-下载GIF并将其调整为文件大小
我需要下载GIF并将其保存到外部存储中,以便可以通过彩信发送.邮件的限制为300kb,并且大多数GIF太大,因此我需要调整它们的大小.
I need to download a GIF and save it to external storage so I can send it via MMS.Messages have a limit 300kb and most of the GIFs are too large so I need to resize them.
我在项目的其余部分中使用了Glide,因此Glide具有漂亮的功能,从理论上讲,它应该下载经过调整大小的图像.但事实并非如此.
I am using Glide in rest of my project and Glide has a nifty function which should, in theory, download a resized image. But it doesn't.
简而言之,这是我在后台线程中调用的代码:
In short, here's the code I'm calling inside a background thread:
byte[] bytes = Glide.with(context)
.load(url)
.asGif()
.toBytes()
.into(250, 250)
.get();
file = new File(fileName);
FileOutputStream fileWriter = new FileOutputStream(file);
fileWriter.write(bytes);
fileWriter.flush();
fileWriter.close();
下载的文件仍然保持其原始大小,该大小超出了MMS的300kb限制,但应为250x250像素.
Downloaded files still keep their original size which is above the MMS limit of 300kb whereas they should be 250x250 pixels.
在Glide Github上提出了相同的问题,并在那里得到了答案.显然,除非使用fitCenter()(或任何其他)转换,否则Glide只会调整大于500 x 500的图像的大小.
Asked the same question on Glide Github and got the answer there. Apparently Glide will only resize images that are larger than 500 x 500, unless a fitCenter() (or any other) transformation is used.
因此,要调整.gif文件的大小,请使用以下代码:
So, to resize the .gif file, use this code:
byte[] bytes = Glide.with(context)
.load(url)
.asGif()
.toBytes()
.transform(new GifDrawableTransformation(new CenterCrop(context), Glide.get(context).getBitmapPool()))
.into(250, 250)
.get();