所以我有这个奇怪的问题。 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();
}
}
它可以很好地保存文件,但它似乎不会因为某种原因在很小的时间内捕获图像。
答案 0 :(得分:1)
首先确保您的应用已启用存储权限:
转到设备设置>设备>应用程序>应用程序管理器>"您的应用">权限>启用存储权限!
清单中的权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
因此,如果您想在文件存储中创建自己的目录,可以使用somethibng,如:
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;
希望这有帮助!
答案 1 :(得分:0)
试试这段代码:
public static String saveImageInExternalCacheDir(Context context, Bitmap bitmap, String myfileName) {
String fileName = myfileName.replace(' ', '_') + getCurrentDate().toString().replace(' ', '_').replace(":", "_");
String filePath = (context.getExternalCacheDir()).toString() + "/" + fileName + ".jpg";
try {
FileOutputStream fos = new FileOutputStream(new File(filePath));
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, fos);
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
return filePath;
}