位图在保存时会失去透明度 [英] Bitmap loses transparency when it's saved

查看:121
本文介绍了位图在保存时会失去透明度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试将位图保存到外部图片目录时出现问题。当我使用Bitmap.compress函数保存它时,位图失去了透明度并使背景变黑。但是,当我将位图传递给一个图像视图并在活动中显示它时,它看起来很好,而且是透明的。仅当我尝试保存时,透明度才会变为黑色。

我不得不说,我使用两个位图和Porterduff模式在位图上绘制路径,并且只显示绘制路径中的图片,所有其他像素都应该被截断或透明。

下面是创建路径位图的函数:

private void createPathBitmap(RectF rect, Bitmap bitmap, Path path) {
    RectF tmpRect = new RectF(rect);
    Bitmap src = Bitmap.createBitmap(bitmap, (int) tmpRect.left, (int) tmpRect.top, (int) tmpRect.width(), (int) tmpRect.height());
    Bitmap dst = Bitmap.createBitmap(src.getWidth(), src.getHeight(), Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(dst);

    Paint paint = new Paint();
    paint.setAntiAlias(true);
    paint.setStyle(Paint.Style.STROKE);
    paint.setStrokeCap(Paint.Cap.ROUND);
    paint.setStrokeJoin(Paint.Join.ROUND);
    paint.setStrokeWidth(mDisplayDensity * SnippetLayer.PATH_DIAMETER);
    path.offset(-rect.left, -rect.top);
    canvas.drawPath(path, paint);
    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
    RectF srcRect = new RectF(0, 0, rect.width(), rect.height());
    canvas.drawBitmap(src, null, srcRect, paint);
    BitmapManager.sBitmapSnippet = dst;
}

下面是将该位图保存到外部存储的方法:

 SimpleDateFormat dateFormat = new SimpleDateFormat("HH_mm_ss_dd_MM_yyyy");
        File snippetFile = new File(picDir, fileName+"_"+dateFormat.format(new Date())+".png");
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(snippetFile);
            BitmapManager.sBitmapSnippet.setHasAlpha(true);
            BitmapManager.sBitmapSnippet.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
            fileOutputStream.flush();
            fileOutputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

图片仅显示在路径中,包围框的睡觉为黑色,不透明。 感谢您的帮助。

推荐答案

我正在使用Compress()方法将位图写入输出流:

bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);

使用PNG格式很重要。JPEG将透明背景转换为黑色。

这篇关于位图在保存时会失去透明度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆