当前位置 : 主页 > 编程语言 > java >

保存资源ID为图片,并保存在本地

来源:互联网 收集:自由互联 发布时间:2021-06-28
gistfile1.txt /** * 存储资源为ID的图片 * @param id ID * @param name 图片路径 */ public static String saveDrawableById(Context context, int id) { //文件名 String name = System.currentTimeMillis() + ".png"; Drawable drawable =
gistfile1.txt
/**
     * 存储资源为ID的图片
     * @param id ID
     * @param name 图片路径
     */
    public static String saveDrawableById(Context context, int id) {
        //文件名
        String name = System.currentTimeMillis() + ".png";

        Drawable drawable = context.getResources().getDrawable(id);

        if(drawable == null)
            return "";
        Bitmap bitmap = ((BitmapDrawable)drawable).getBitmap();

        // 创建一个位于SD卡上的文件
        File file = new File(context.getExternalCacheDir(), name);
        FileOutputStream out = null;
        try{
            // 打开指定文件输出流
            out = new FileOutputStream(file);
            // 将位图输出到指定文件
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
            out.close();

            return file.getPath();

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

        return "";
    }
网友评论