0

我使用此代码保存图像,但需要很长时间。有时需要 10 秒或更长时间。我减小了位图大小,它有帮助。但它也降低了质量。如何在不降低质量和速度的情况下以原始大小保存位图?

String imageName = UUID.randomUUID().toString();

    String root = Environment.getExternalStorageDirectory().toString();

    File myDir = new File(root, "/removeBG");
    if (!myDir.exists()) {
        myDir.mkdirs();
    }
    String fname;
    if (imgBackground.getDrawable() != null)
        fname = imageName + ".jpg";
    else
        fname = imageName + ".png";

    File file = new File(myDir, fname);
    if (file.exists()) {
        file.delete();
    }
    try {
        file.createNewFile(); // if file already exists will do nothing
        FileOutputStream out = new FileOutputStream(file);
        bitmap = CropBitmapTransparency(bitmap);
        bitmap = resizeBitmap(bitmap, MAX_SIZE, MAX_SIZE);
        if (imgBackground.getDrawable() != null)

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

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

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

    MediaScannerConnection.scanFile(this, new String[]{file.toString()}, new String[]{file.getName()}, null);
    

我搜索这个问题并找到这样的灵魂

public static void create(OutputStream os,int cols,int rows,int r,int  g,int  b,int  a)  {     
        ImageInfo imi = new ImageInfo(cols, rows, 8, true); // 8 bits per channel, alpha
        PngWriter png = new PngWriter(os, imi);
        // just a hint to the coder to optimize compression+speed:
        png.setFilterType(FilterType.FILTER_NONE); 
        ImageLineByte iline = new ImageLineByte (imi);
        byte[] scanline = iline.getScanlineByte();// RGBA
        for (int col = 0,pos=0; col < imi.cols; col++) { 
           scanline[pos++]=(byte) r;  
           scanline[pos++]=(byte) g;
           scanline[pos++]=(byte) b;
           scanline[pos++]=(byte) a;
        }
        for (int row = 0; row < png.imgInfo.rows; row++) {
           png.writeRow(iline);
        }
        png.end();   
 }

我太困惑了。我不知道如何使用它。

4

1 回答 1

0
MediaStore.Images.Media.insertImage (getContext ().getContentResolver (),
                                    imgBitmap, nameFull.getText ().toString ().trim (), 
"");

尝试使用您自己的变量名称。这对我有用

于 2021-01-25T06:59:37.587 回答