How to save GIF image in sdcard?

后端 未结 2 1713
北恋
北恋 2020-12-18 11:31

I am new android and I want to save GIF image in sdcard through android programming. Currently I had done some code from google to save GIF image in sdcard. But When I am sa

2条回答
  •  萌比男神i
    2020-12-18 12:09

    Use the provide code and make sure to add WRITE_EXTERNAL_STORAGE in meaifest.

     protected void saveGifToInternalStorage(String fileName, URL url) {
        try {
            String PATH = Environment.getExternalStorageDirectory() + "/download/your_app_name";
            File file = new File(PATH);
            if(!file.exists()) {
                file.mkdirs();
            }
    
            long startTime = System.currentTimeMillis();
            Log.d(TAG, "download begining");
            Log.d(TAG, "download url:" + url);
            Log.d(TAG, "downloaded file name:" + fileName);
            /* Open a connection to that URL. */
            URLConnection ucon = url.openConnection();
    
            /*
             * Define InputStreams to read from the URLConnection.
             */
            InputStream is = ucon.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is);
    
            /*
             * Read bytes to the Buffer until there is nothing more to read(-1).
             */
            ByteArrayBuffer baf = new ByteArrayBuffer(50);
            int current = 0;
            while ((current = bis.read()) != -1) {
                baf.append((byte) current);
            }
    
            /* Convert the Bytes read to a String. */
            File outputFile = new File(file, fileName+".gif");
            FileOutputStream fos = new FileOutputStream(outputFile);
            fos.write(baf.toByteArray());
            fos.close();
            Log.d(TAG, "download ready in"
                    + ((System.currentTimeMillis() - startTime) / 1000)
                    + " sec");
    
        } catch (IOException e) {
            Log.d(TAG, "Error: " + e);
        }
    }
    

提交回复
热议问题