如何将Gif文件从url保存到我的手机中?

时间:2018-09-02 06:59:54

标签: java android

我是一名初学者Android开发人员(毕业于Uniiv并寻找工作)

因此,我正在开发的应用程序中上传了如此多的GIF文件,其他人正在下载并保存他们的手机。

我可以下载GIF或其他图像文件,然后保存到我的目录中。但是问题是Bitmap.compress不支持GIF(仅png,jpg..etc)。

因此,我将GIF文件压缩为png或jpg。不出所料,图像没有动画。我的图像都是GIF文件。如何压缩GIF文件并保存到目录中?

以下是我的代码

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    final ViewGroup view1 = (ViewGroup) inflater.inflate(R.layout.fragment1, container, false);
    Button button = (Button) view1.findViewById(R.id.saveBtn);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

        }
    });

    new Thread(new Runnable() {
        @Override
        public void run() {
            try{
                bm = getBitmap(myUrl);
            }catch (Exception e){

            }finally {
                if(bm != null){
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {

                            getAlbumStorageDir(albumName,"GifImage_"+num);
                            num++;

                        }//end run()
                    });
                }
            }
        }
    }).start();

    return view1;
}

private Bitmap getBitmap(String url) {
    URL imgUrl = null;
    HttpURLConnection connection = null;
    InputStream is = null;

    Bitmap retBitmap = null;

    try{
        imgUrl = new URL(url);
        connection = (HttpURLConnection) imgUrl.openConnection();
        connection.setDoInput(true); 
        connection.connect();
        is = connection.getInputStream(); // get inputstream
        retBitmap = BitmapFactory.decodeStream(is);
    }catch(Exception e) {
        e.printStackTrace();
        return null;
    }finally {
        if(connection!=null) {
            connection.disconnect();
        }
        return retBitmap;
    }
}

public void getAlbumStorageDir(String albumName, String imageName) {

    String root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath();
    String folder_name = "/" + albumName + "/";
    String file_name = imageName;
    String string_path = root + folder_name;
    String save_path = string_path + file_name;

    File file_path;

    try {
        file_path = new File(string_path);
        if (!file_path.isDirectory()) {
            file_path.mkdirs();
        }
        FileOutputStream out = new FileOutputStream(string_path + file_name);
        bm.compress(Bitmap.CompressFormat.JPEG, 100, out);
        out.flush();
        out.close();
        getActivity().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://"+save_path))); //갤러리 갱신
        Toast.makeText(getContext(), "save success ", Toast.LENGTH_SHORT).show();

    } catch (IOException e) {
        e.printStackTrace();
    }
}

}

0 个答案:

没有答案