将位图保存到磁盘时,实体路径会显示伪像 [英] When saving bitmap to disk, solid paths show artifacts

查看:91
本文介绍了将位图保存到磁盘时,实体路径会显示伪像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用路径"绘制简单2D几何图形的应用程序.形状均为纯色,有时为alpha< 255,并可能以线条装饰.在绘制几何图形的视图中,绘制事物的方式从来没有问题.但是,当我使用相同的代码绘制到位图,然后将其另存为JPEG(质量为100)或PNG时,输出文件的纯色区域中始终存在相同的伪像.这是一种斑点现象,通常与JPEG压缩相关.

I have an app that draws simple 2D geometry using Paths. The shapes are all solid colors, sometimes with alpha < 255, and may be decorated with lines. In the View that draws the geometry, there has never been an issue with how things get drawn. However, when I use the same code to draw to a Bitmap, and then save it as either a JPEG (with 100 quality) or PNG, there is always the same artifacting in the solid-colored areas of the output files. It's a sort of mottling that is usually associated with JPEG compression.

查看屏幕截图:

保存的图像:

放大工件:

我尝试了以下

  • 保存为PNG和JPEG
  • 打开和关闭抖动和抗锯齿
  • 增加位图的DPI,还允许位图使用其默认API
  • 将我用作摄像头的矩阵应用于几何图形表示,而不是将其应用于画布的位图
  • 在整个应用范围内打开和关闭硬件加速
  • 使用第三方库将位图保存到.bmp文件

所有产品都产生相同的伪像,既不会使它变得更糟也不会变得更好.

All yield the same artifacts, neither making it worse nor better.

public class MainActivity extends AppCompatActivity {
Context context;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    this.context = getApplicationContext();
}

// button OnClick listener
public void saveImage(View view) {
    new saveBitmapToDisk().execute(false);
}

public Bitmap getBitmap() {
    final int bitmapHeight = 600, bitmapWidth = 600;
    Bitmap bitmap = Bitmap.createBitmap(bitmapWidth, bitmapHeight, Bitmap.Config.ARGB_8888);
    Canvas bitmapCanvas = new Canvas(bitmap);

    float[] triangle = new float[6];
    triangle[0] = bitmapWidth / 2;
    triangle[1] = 0;
    triangle[2] = 0;
    triangle[3] = bitmapHeight / 2;
    triangle[4] = bitmapWidth / 2;
    triangle[5] = bitmapHeight / 2;

    Path solidPath = new Path();
    Paint solidPaint = new Paint();
    solidPaint.setStyle(Paint.Style.FILL);

    solidPath.moveTo(triangle[0], triangle[1]);

    for(int i = 2; i < triangle.length; i += 2)
        solidPath.lineTo(triangle[i], triangle[i+1]);

    solidPath.close();

    solidPaint.setColor(Color.GREEN);
    bitmapCanvas.drawPath(solidPath, solidPaint);
    return bitmap;
}

private class saveBitmapToDisk extends AsyncTask<Boolean, Integer, Uri> {
    Boolean toShare;

    @Override
    protected Uri doInBackground(Boolean... shareFile) {
        this.toShare = shareFile[0];
        final String appName = context.getResources().getString(R.string.app_name);
        final String IMAGE_SAVE_DIRECTORY = String.format("/%s/", appName);
        final String fullPath = Environment.getExternalStorageDirectory().getAbsolutePath() + IMAGE_SAVE_DIRECTORY;
        File dir, file;

        try {
            dir = new File(fullPath);
            if (!dir.exists())
                dir.mkdirs();

            OutputStream fOut;

            file = new File(fullPath, String.format("%s.png", appName));

            for (int suffix = 0; file.exists(); suffix++)
                file = new File(fullPath, String.format("%s%03d.png", appName, suffix));

            file.createNewFile();
            fOut = new FileOutputStream(file);

            Bitmap saveBitmap = getBitmap();
            saveBitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
            fOut.flush();
            fOut.close();
            MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getAbsolutePath(), file.getName(), file.getName());

        } catch (OutOfMemoryError e) {
            Log.e("MainActivity", "Out of Memory saving bitmap; bitmap is too large");
            return null;
        } catch (Exception e) {
            Log.e("MainActivity", e.getMessage());
            return null;
        }

        return Uri.fromFile(file);
    }

    @Override
    protected void onPostExecute(Uri uri) {
        super.onPostExecute(uri);
        Toast.makeText(context, "Image saved", Toast.LENGTH_SHORT).show();
    }
}
}

推荐答案

  1. 我用PNG测试了您的程序,文件中没有任何瑕疵
  2. 这些伪像是JPEG压缩的结果

线

MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getAbsolutePath(), file.getName(), file.getName());

正在导致转换为jpeg.

was causing the conversion to jpeg.

保存图像的正确方法是

ContentValues values = new ContentValues();
values.put(Images.Media.DATE_TAKEN, System.currentTimeMillis());
values.put(Images.Media.MIME_TYPE, "image/png");
values.put(MediaStore.MediaColumns.DATA, file.getAbsolutePath());
context.getContentResolver().insert(Images.Media.EXTERNAL_CONTENT_URI, values);

这是我的简化测试程序,可以直接发送生成的文件

Here is my simplified test program that sends the generated file directly

public class Test2Activity extends Activity {
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    new saveBitmapToDisk().execute();
  }

  public Bitmap getBitmap() {
    final int bitmapHeight = 600, bitmapWidth = 600;
    Bitmap bitmap = Bitmap.createBitmap(bitmapWidth, bitmapHeight, Bitmap.Config.ARGB_8888);
    Canvas bitmapCanvas = new Canvas(bitmap);

    Paint solidPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    solidPaint.setStyle(Paint.Style.FILL);
    solidPaint.setColor(Color.RED);
    bitmapCanvas.drawCircle(300, 300, 200, solidPaint);

    return bitmap;
  }

  private class saveBitmapToDisk extends AsyncTask<Void, Void, Uri> {
    Boolean toShare;

    @Override
    protected Uri doInBackground(Void... shareFile) {
      Context context = Test2Activity.this;
      try {
        File file = new File(context.getExternalFilesDir(null), "test.png");
        FileOutputStream fOut = new FileOutputStream(file);

        Bitmap saveBitmap = getBitmap();
        saveBitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
        fOut.flush();
        fOut.close();
        return Uri.fromFile(file);
      } catch (OutOfMemoryError e) {
        Log.e("MainActivity", "Out of Memory saving bitmap; bitmap is too large");
        return null;
      } catch (Exception e) {
        Log.e("MainActivity", e.getMessage());
        return null;
      }

    }

    @Override
    protected void onPostExecute(Uri uri) {
      Context context = Test2Activity.this;
      Toast.makeText(context, "Image saved", Toast.LENGTH_SHORT).show();

      final Intent intent = new Intent(android.content.Intent.ACTION_SEND);
      intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
      intent.putExtra(Intent.EXTRA_STREAM, uri);
      intent.setType("image/png");
      Test2Activity.this.startActivity(intent);
    }
  }
}

这篇关于将位图保存到磁盘时,实体路径会显示伪像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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