使用Picasso从url保存图像?
我在尝试使用API Picasso保存图像。要做到这一点,我试图用Target
来保存,但我无法完成这项工作。使用Picasso从url保存图像?
我该怎么做?
试图
//save image
public static void imageDownload(Context ctx){
Picasso.with(ctx)
.load("http://blog.concretesolutions.com.br/wp-content/uploads/2015/04/Android1.png")
.into(getTarget("http://blog.concretesolutions.com.br/wp-content/uploads/2015/04/Android1.png"));
}
//target to save
private static Target getTarget(final String url){
Target target = new Target(){
@Override
public void onBitmapLoaded(final Bitmap bitmap, Picasso.LoadedFrom from) {
new Thread(new Runnable() {
@Override
public void run() {
//Log.i("PRODUTOS_FOLDER", CreateAppFolder.getProdutosFolder());
File file = new File(Environment.getExternalStorageDirectory() + url);
try {
file.createNewFile();
FileOutputStream ostream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, ostream);
ostream.flush();
ostream.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
@Override
public void onBitmapFailed(Drawable errorDrawable) {
}
@Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
};
return target;
}
异常
java.io.IOException: open failed: ENOENT (No such file or directory)
已解决。现在工作正常!
我做
//save image
public static void imageDownload(Context ctx, String url){
Picasso.with(ctx)
.load("http://blog.concretesolutions.com.br/wp-content/uploads/2015/04/Android1.png")
.into(getTarget(url));
}
//target to save
private static Target getTarget(final String url){
Target target = new Target(){
@Override
public void onBitmapLoaded(final Bitmap bitmap, Picasso.LoadedFrom from) {
new Thread(new Runnable() {
@Override
public void run() {
File file = new File(Environment.getExternalStorageDirectory().getPath() + "/" + url);
try {
file.createNewFile();
FileOutputStream ostream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 80, ostream);
ostream.flush();
ostream.close();
} catch (IOException e) {
Log.e("IOException", e.getLocalizedMessage());
}
}
}).start();
}
@Override
public void onBitmapFailed(Drawable errorDrawable) {
}
@Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
};
return target;
}
它给了我错误:打开失败:EACCES(权限被拒绝)。在清单上我已经声明
@AEMLoviji首先使用'Environment.getExternalStorageState == Environment.MEDIA_MOUNTED'检查外部存储状态 – NineToeNerd
为什么不把hash图像url和将其转换为长整数,用于生成文件名? – zyamys
我可以看到2个可能出现的问题:
- 试图保存到外部存储没有写权限在您的清单
- 尝试更改文件名,以便它不是整个网址,这可能是您的问题,因为您的网址中的字符不能作为文件名字符有效。
我使用了这段代码。并在我的Android清单我decalred permision为:
我认为你需要检查你是否真正要求的权限。 在Android中,从版本6.0开始,权限是动态的。要么你必须在运行时请求它,要么只是将你的targetSdk版本降级到22.
你的问题究竟是什么,回调不起作用,或者你的位图没有保存,或者其他什么? –
@VasylGlodan抛出异常'java.io.IOException:打开失败:ENOENT(没有这样的文件或目录)' – FernandoPaiva
嗯,我不确定,但你的文件的路径应该看起来像这样'/ storage/emulated/0/http:// blog.concretesolutions.com.br/wp-content/uploads/2015/04/Android1.png',系统尝试建立一个名为'/storage/emulated/0/http://blog.concretesolutions的目录。 com.br/wp-content/uploads/2015/04 /',但没有这样的目录。尝试从文件名中删除所有特殊字符。 –