Android 如何以最快的方式将图像URL转换为位图并保存?
使用-Android 如何以最快的方式将图像URL转换为位图并保存?,android,file,url,bitmapimage,Android,File,Url,Bitmapimage,使用-BitmapFactory.decodeStream(url.openConnection().getInputStream()) 有没有更好的方法将url转换为位图并将图像保存到设备中?因为我的应用程序应该离线工作。 我一直在使用多种方法保存图像,如asynctask、毕加索等。所有这些都需要花费太多的时间。这就是为什么我要问这个问题。试试这段代码。它很有效… 它将下载图像格式的url并保存在手机的SD卡中 try { URL url = new URL("Ente
BitmapFactory.decodeStream(url.openConnection().getInputStream())
有没有更好的方法将url转换为位图
并将图像
保存到设备中?因为我的应用程序应该离线工作。
我一直在使用多种方法保存图像,如asynctask、毕加索等。所有这些都需要花费太多的时间。这就是为什么我要问这个问题。试试这段代码。它很有效… 它将下载图像格式的url并保存在手机的SD卡中
try
{
URL url = new URL("Enter the URL to be downloaded");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();
File SDCardRoot = Environment.getExternalStorageDirectory().getAbsoluteFile();
String filename="downloadedFile.png";
Log.i("Local filename:",""+filename);
File file = new File(SDCardRoot,filename);
if(file.createNewFile())
{
file.createNewFile();
}
FileOutputStream fileOutput = new FileOutputStream(file);
InputStream inputStream = urlConnection.getInputStream();
int totalSize = urlConnection.getContentLength();
int downloadedSize = 0;
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ( (bufferLength = inputStream.read(buffer)) > 0 )
{
fileOutput.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
Log.i("Progress:","downloadedSize:"+downloadedSize+"totalSize:"+ totalSize) ;
}
fileOutput.close();
if(downloadedSize==totalSize) filepath=file.getPath();
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
filepath=null;
e.printStackTrace();
}
Log.i("filepath:"," "+filepath) ;
return filepath;
你可以用。从Url
加载Bitmap
并缓存它们很容易
所以,它节省了你的时间
你只要加上这一行就行了
Picasso.with(getContext()).load(Uri).into(ImageView);
Glide.with(这个)
.负载(strUrl)
.into(新的SimpleTarget(){
@凌驾
公共资源就绪(@NonNull Drawable resource,@Nullable Transition为什么现在要将url转换为位图加载图像时提供的一个日库您可以使用毕加索或Glide图像库进行此操作。@Athira请通过浏览器下载并检查分辨率来检查图像的大小。如果其大于要求,您可以通过Glide或Picas覆盖图像大小因此,库在下载时我希望在设备离线时显示图像。您能够改进代码的唯一方法是使用方法分析或其他工具来确定所花费的时间。例如,如果时间只花在下载过程中,则不太可能加速。您可以添加您的建议以供评论。请不要将其添加为答案。@Joker这可能是他的问题的答案。如果您想添加答案,请上传代码片段以获取帮助或stackoverflow答案链接,这将非常有用。请查看指南@Joker OK,谢谢。但是,也许毕加索是一个很好的解决方案,看看代码片段。好的,请做什么“saveMyBitmap”?它给我一个错误,无法将“方法”解析为(匿名com.bumptech.glide.request.target.SaimpleTarget“它是将位图保存到文件的函数,如…try(FileOutputStream out=new FileOutputStream(filename)){bmp.compress(bitmap.CompressFormat.PNG,100,out);//bmp是位图实例//PNG是无损格式,压缩因子(100)被忽略}catch(IOException e){e.printStackTrace();}
Glide.with(this)
.load(strUrl)
.into(new SimpleTarget<Drawable>() {
@Override
public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
saveMyBitmap(((BitmapDrawable) resource).getBitmap());
}
});