gpt4 book ai didi

android - 保存 Android ImageView 位图

转载 作者:行者123 更新时间:2023-11-30 02:47:20 25 4
gpt4 key购买 nike

所以我遇到了这个奇怪的问题。 9/10 次它会工作得很好,但那 10% 根本不起作用。

我只是想拥有一个可以缩放和平移的 ImageView。效果很好-然后我尝试将 imageView 保存到手机本身。大多数情况下,这是它可以工作的地方,但有时它会将图像保存为黑屏……而不是 ImageView 上实际显示的内容。

这是我保存 ImageView 的代码:

protected void saveZoomedImage(){

//create ImageView Bitmap
RelativeLayout tableContent;
tableContent=(RelativeLayout)findViewById(R.id.imgHolder);
tableContent.measure(MeasureSpec.makeMeasureSpec(tableContent.getLayoutParams().width, MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(tableContent.getLayoutParams().height,MeasureSpec.EXACTLY));
tableContent.setDrawingCacheEnabled(true);
final Bitmap screenshot = Bitmap.createBitmap(tableContent.getDrawingCache());
tableContent.setDrawingCacheEnabled(true);

//save file
File folder = new File(Environment.getExternalStorageDirectory () + "/thedir");
if(!folder.exists()){
folder.mkdir();
}
String exsistingFileName=Environment.getExternalStorageDirectory().getAbsolutePath() + "/thedir";
FileOutputStream fos = null;
try {
fos = new FileOutputStream(exsistingFileName + "/image.jpg");
screenshot.compress(Bitmap.CompressFormat.JPEG, 90, fos);
fos.flush();
fos.close();

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

}

它可以很好地保存文件,但似乎由于某种原因在一小段时间里它没有捕捉到图像。

最佳答案

首先确保您的应用已启用存储权限:

转到设备设置>设备>应用程序>应用程序管理器>“您的应用程序”>权限>启用存储权限!

list 中的权限:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

所以,如果你想在你的文件存储中创建你自己的目录,你可以使用像这样的东西:

String myDate = getCurrentDateAndTime();
FileOutputStream outStream = null;
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File(sdCard.getAbsolutePath() + "/YourFolderName");
dir.mkdirs();
String fileName = "YourFileName_"+myDate+".jpg";
File outFile = new File(dir, fileName);
outStream = new FileOutputStream(outFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
outStream.flush();
outStream.close();
//to refresh the gallery
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
intent.setData(Uri.fromFile(file));
sendBroadcast(intent);

辅助函数:

private String getCurrentDateAndTime() {
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
String formattedDate = df.format(c.getTime());
return formattedDate;

希望这对您有所帮助!

关于android - 保存 Android ImageView 位图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24808728/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com