如何将图像保存到加载Glide的本地存储中?

时间:2018-02-23 13:52:40

标签: android imageview android-imageview android-glide

我有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())));
                }
            }

        });

    }
}

Log Cat

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)

2 个答案:

答案 0 :(得分:0)

//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())));
        }
            }

答案 1 :(得分:0)

AsyncTask,可以用来下载Image。这个过程将在后台线程中。

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>