使用Picasso从网址保存图片?

时间:2015-09-26 16:29:15

标签: android picasso

我尝试使用API​​ Picasso保存图像。要做到这一点,我尝试使用Target进行保存,但我无法完成这项工作。

我怎么能这样做?

尝试

//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)

5 个答案:

答案 0 :(得分:29)

解决。现在工作正常!

我做了

for i in range(1,10) + [chr(x) for x in range(ord('a'), ord('z')+1)]:
    print i

答案 1 :(得分:3)

我可以看到两个可能的问题:

  1. 尝试在清单中没有写入权限的情况下保存到外部存储
  2. 尝试更改文件名,使其不是整个网址,这可能是您的问题,因为网址中的字符无法作为文件名字符生效。

答案 2 :(得分:1)

  

我修改了解决方案,添加权限和按钮来加载和保存图片, PhotoLoader 类保持不变!

private static final String[] STORAGE_PERMISSIONS = { Manifest.permission.WRITE_EXTERNAL_STORAGE};
    ImageView imageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        imageView = (ImageView) findViewById(R.id.imageView);

        verifyPermissions();
    }
    public void save(View view)
    {
        Picasso.with(this)
                .load("https://www.w3schools.com/howto/img_fjords.jpg")
                .into(new PhotoLoader("myImg.jpg" , imageView));
    }

    public void verifyPermissions()
    {
        // This will return the current Status
        int permissionExternalMemory = ActivityCompat.checkSelfPermission(MainActivity.this,Manifest.permission.WRITE_EXTERNAL_STORAGE);

        if(permissionExternalMemory != PackageManager.PERMISSION_GRANTED)
        {
            // If permission not granted then ask for permission real time.
            ActivityCompat.requestPermissions(MainActivity.this,STORAGE_PERMISSIONS,1);
        }
    }

答案 3 :(得分:0)

我认为你需要检查一下你是否真的要求获得许可。 在Android中,权限从6.0版开始是动态的。您必须在运行时请求它或者只是将targetSdk版本降级到22。

答案 4 :(得分:0)

我的 kotlin 解决方案,将文件存储到内部存储中,无需用户许可:

因为我必须一次下载多个图像,所以必须创建一个名为 shareTargetsArray 的 MutableList 并用多个目标填充它,否则垃圾收集器会删除它们,除了最后一个一。只需记住在完成后清理该数组。

    private var shareTargetsArray: MutableList<Target?> = ArrayList()

    fun downloadImage(context: Context, url: String?, slug: String) {

        val shareTarget = object : Target {
            override fun onBitmapLoaded(bitmap: Bitmap, from: LoadedFrom?) {

                    val contextWrapper = ContextWrapper(context)
                    val directory: File =
                        contextWrapper.getDir("customDirectory", Context.MODE_PRIVATE)
                    val file = File(directory, slug + ".png")

                    var outputStream: FileOutputStream? = null

                    try {
                        outputStream = FileOutputStream(file)

                        bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream)
                        outputStream.flush()
                    } catch (e: IOException) {
                        e.printStackTrace()
                    } finally {
                        try {
                            outputStream!!.close()
                        } catch (e: IOException) {
                            e.printStackTrace()
                        }
                    }
                }

            override fun onBitmapFailed(e: java.lang.Exception?, errorDrawable: Drawable?) {}

            override fun onPrepareLoad(placeHolderDrawable: Drawable?) {}
        }

        shareTargetsArray.add(shareTarget)
        Picasso.get().load(url).into(shareTarget)
    }
}

文件下载在/data/data/com.***.***/customDirectory/ 您可以使用 View > Tool Windows > Device File Explorer

检查它们