如何使用Glide将图片保存到本地存储?

6

我有一个ImageView,使用Glide库从服务器加载了一张照片。我有一个save按钮,希望在加载后单击该按钮时将图像保存到相册和内部存储中。我已经尝试了几种可能性,但都没有成功,因为单击按钮后似乎什么也没发生。

    public class ImagePreviewActivity extends AppCompatActivity {
    ImageView imageView;
    final File myDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/SmartPhoto"); 
   boolean success = false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_image_preview);
        imageView  = findViewById(R.id.image_preview);
     saveImage();

    }

    private void saveImage() {
        TextView mSave = findViewById(R.id.save_img);
        mSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final Random generator = new Random();
                int n = 10000;
                n = generator.nextInt(n);
                final String fname = "image" + n + ".png";
                myDir.mkdirs();
                File image = new File(myDir, fname);
                imageView.setDrawingCacheEnabled(true);
                Bitmap bitmap = imageView.getDrawingCache();
                // Encode the file as a PNG image.
                FileOutputStream outStream;
                try {
                    outStream = new FileOutputStream(image);
                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
                    /* 100 to keep full quality of the image */
                    outStream.flush();
                    outStream.close();
                    success = true;
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                if (success) {
                    Toast.makeText(getApplicationContext(),"Saved", Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(getApplicationContext(),"not saved", Toast.LENGTH_LONG).show();
                }
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                    final Intent scanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                    final Uri contentUri = Uri.fromFile(image);
                    scanIntent.setData(contentUri);
                    sendBroadcast(scanIntent);
                } else {
                    sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://mnt/sdcard/" + Environment.getExternalStorageDirectory())));
                }
            }

        });

    }
}

日志记录器

02-24 14:40:41.288 1567-1575/? E/System: Uncaught exception thrown by finalizer
02-24 14:40:41.289 1567-1575/? E/System: java.lang.IllegalStateException: Binder has been finalized!
                                             at android.os.BinderProxy.transactNative(Native Method)
                                             at android.os.BinderProxy.transact(Binder.java:622)
                                             at android.net.INetworkStatsSession$Stub$Proxy.close(INetworkStatsSession.java:476)
                                             at android.app.usage.NetworkStats.close(NetworkStats.java:382)
                                             at android.app.usage.NetworkStats.finalize(NetworkStats.java:118)
                                             at java.lang.Daemons$FinalizerDaemon.doFinalize(Daemons.java:223)
                                             at java.lang.Daemons$FinalizerDaemon.run(Daemons.java:210)
                                             at java.lang.Thread.run(Thread.java:761)

不要为了图像质量而使用DrawingCache。将图片作为位图下载并保存到SD卡。 - ADM
之前尝试过了,结果一样。 - Ben Ajax
什么相同的结果?这是正确的方法。 - ADM
@BenAjax 请尝试我的答案并告诉我是否有任何问题。 - EL TEGANI MOHAMED HAMAD GABIR
@BenAjax,如果您计划针对23版本及以上的Android进行开发,可以采用简单且代码量少的方式添加运行时权限。好的。 - EL TEGANI MOHAMED HAMAD GABIR
2个回答

0

AsyncTask 可以用于下载图像。该过程将在后台线程中执行。

class DownloadImage extends AsyncTask<String,Integer,Long> {

    String strFolderName;
    @Override
    protected void onPreExecute() {
        super.onPreExecute();

    }
    @Override
    protected Long doInBackground(String... aurl) {
        int count;
        try {
            URL url = new URL((String) aurl[0]);
            URLConnection conexion = url.openConnection();
            conexion.connect();
            String targetFileName="Name"+".rar";//Change name and subname
            int lenghtOfFile = conexion.getContentLength();
            String PATH = Environment.getExternalStorageDirectory()+ "/"+downloadFolder+"/";
            File folder = new File(PATH);
            if(!folder.exists()){
                folder.mkdir();//If there is no folder it will be created.
            }
            InputStream input = new BufferedInputStream(url.openStream());
            OutputStream output = new FileOutputStream(PATH+targetFileName);
            byte data[] = new byte[1024];
            long total = 0;
            while ((count = input.read(data)) != -1) {
                total += count;

                output.write(data, 0, count);
            }
            output.flush();
            output.close();
            input.close();
        } catch (Exception e) {}
        return null;
    }

    protected void onPostExecute(String result) {
    }
}

你可以这样调用这个类:new DownloadImage().execute(“yoururl”);

别忘了在清单文件中添加以下权限。

<uses-permission android:name="android.permission.INTERNET"> </uses-permission>
  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>

有趣。我会尝试并回来的。 - Ben Ajax
if any doubt , just reply - Vivek Patel
如何将正确的上下文传递给进度对话框? - Ben Ajax
只需移除进度对话框。 - Vivek Patel
我尝试了你的代码。我还在 preExecute 中加入了一个进度对话框。任务已经执行,但我仍然无法在应用程序中找到图像或目录。它没有被下载。 - Ben Ajax
让我们在聊天中继续这个讨论 - Ben Ajax

-1
//out oncreate
    final File myDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/SmartPhoto");
    boolean success = false;


    //inside oncreate
      mSave = (TextView) findViewById(R.id.save);
        imageView  = (ImageView) findViewById(R.id.header_cover_image);

        mSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view)
            {
                saveImage();
            }
        });


    public void saveImage()
    {
                final Random generator = new Random();
                int n = 10000;
                n = generator.nextInt(n);
                final String fname = "image" + n + ".png";
                myDir.mkdirs();
                File image = new File(myDir, fname);
                imageView.setDrawingCacheEnabled(true);
                Bitmap bitmap = imageView.getDrawingCache();
                // Encode the file as a PNG image.
                FileOutputStream outStream;
                try {
                    outStream = new FileOutputStream(image);
                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
                    /* 100 to keep full quality of the image */
                    outStream.flush();
                    outStream.close();
                    success = true;
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (success) {
                    Toast.makeText(getApplicationContext(),"Saved", Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(getApplicationContext(),"not saved", Toast.LENGTH_LONG).show();
                }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            final Intent scanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            final Uri contentUri = Uri.fromFile(image);
            scanIntent.setData(contentUri);
            sendBroadcast(scanIntent);
        } else {
            sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://mnt/sdcard/" + Environment.getExternalStorageDirectory())));
        }
            }

请解释一下您使用的两个返回语句。 - Ben Ajax
日志中显示了什么信息?更新了返回语句@BenAjax - EL TEGANI MOHAMED HAMAD GABIR
或者字符串ImagedSavedPath = f.getAbsolutePath(); 然后返回ImagSavedPath; - EL TEGANI MOHAMED HAMAD GABIR
很抱歉,但是返回语句仍然给我带来了问题。它说- 无法从具有void返回类型的方法中返回值。 - Ben Ajax
你的返回是void?!..我的返回是String,它是图像保存路径??!!@BenAjax - EL TEGANI MOHAMED HAMAD GABIR
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接