1

我是一名初学 Android 开发者(大学毕业并找工作)

所以,我正在开发应用程序上传这么多的 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();
    }
}

}

4

0 回答 0