保存图像花费的时间太长



我使用这段代码来保存图像,但它需要很长时间。有时需要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();   
}

我太困惑了。我不知道怎么用它。

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

尝试使用您自己的变量名。

最新更新