我正在使用此代码保存图像。图像保存在具有SD卡插槽的设备中。但是只有内置内存或设备存储的设备(如三星SM-J710F)无法保存图像。
我的代码:
private void saveImageAsJpeg() {
Bitmap bitmap = _paintView.getDrawingCache();
Date d = new Date();
CharSequence s = DateFormat.format("yyyyMMdd-HHmmss", d.getTime()); // MM-dd-yy hh-mm-ss
File file = new File(Environment.getExternalStorageDirectory(),"/dcim/MyImageFolder/"+ s + ".jpg");
Toast.makeText(getApplicationContext(), "Your Image Saved at " + file.getAbsolutePath(), Toast.LENGTH_LONG).show();
try {
if (!file.exists()) {
//file.createNewFile();
file.getParentFile().mkdirs();
}
FileOutputStream ostream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, ostream);
ostream.close();
if (file.toURI() != null)
{
new MediaScannerNotifier(FillColorActivity.this, file.toString(), MIME_PNG);
}
} catch (Exception e) {
e.printStackTrace();
}
}
我在堆栈上经历了多个解决方案,但没有得到正确的解决方案。
答案 0 :(得分:1)
如果要将视图保存为SD卡中的图像,可以尝试以下方法,
public static void saveMyView(View view, Context context) {
Date d = new Date();
CharSequence fileName = DateFormat.format("yyyyMMdd-HHmmss", d.getTime()); // MM-dd-yy hh-mm-ss
final File file;
if(isExternalStorageReadable()) {
file = new File(Environment.getExternalStorageDirectory().getPath(), "MyImageFolder/");
} else {
file = new File(context.getFilesDir().getPath(), "MyImageFolder/");
}
if (!file.exists()) {
file.mkdir();
}
saveBitmapInFile(new File(file.getAbsoluteFile(), fileName + ".jpg"), getBitmapFromView(view), context);
}
public static boolean isExternalStorageReadable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state) ||
Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
return true;
}
return false;
}
private static void saveBitmapInFile(File file, Bitmap bitmap, Context context) {
FileOutputStream out = null;
try {
out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri contentUri = Uri.fromFile(file);
mediaScanIntent.setData(contentUri);
context.sendBroadcast(mediaScanIntent);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static Bitmap getBitmapFromView(View view) {
view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
view.buildDrawingCache();
Bitmap bitmap = Bitmap.createBitmap(view.getMeasuredWidth(), view.getMeasuredHeight(),
Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
canvas.drawColor(Color.WHITE, PorterDuff.Mode.SRC_IN);
Drawable drawable = view.getBackground();
if (drawable != null)
drawable.draw(canvas);
view.draw(canvas);
return bitmap;
}
答案 1 :(得分:0)
试试这个例子希望这会对你有所帮助。在按钮上单击调用selectpic()。
public void selectpic() {
final Dialog myDialog = new Dialog(this);
myDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
myDialog.getWindow().setLayout(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT);
myDialog.setContentView(R.layout.custom_dialog);
myDialog.setTitle("Choose Picture");
Button btncamera = (Button) myDialog.findViewById(R.id.btncamera);
Button btngallery = (Button) myDialog.findViewById(R.id.btngallery);
//EnableRuntimePermission();
//Select Camera
btncamera.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
ClickImageFromCamera() ;
myDialog.cancel();
}
});
//Select image from gallery
btngallery.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
GetImageFromGallery();
myDialog.cancel();
}
});
myDialog.show();
}
public void ClickImageFromCamera() {
CamIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
File sdCardDirectory = new File(Environment.getExternalStorageDirectory(),
"MyFolder/Media/Profile");
sdCardDirectory.mkdirs();
File image = new File(sdCardDirectory, "tempProfilepic" + ".jpg");
uri = Uri.fromFile(image);
CamIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, uri);
CamIntent.putExtra("return-data", true);
startActivityForResult(CamIntent, AppConstants.REQUEST_CAMERA);
}
public void GetImageFromGallery(){
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
//intent.setAction(Intent.ACTION_GET_CONTENT);
try {
intent.putExtra("return-data", true);
startActivityForResult(Intent.createChooser(intent,
"Complete action using"), AppConstants.SELECT_FILE);
} catch (ActivityNotFoundException e) {
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK){
if (requestCode == AppConstants.REQUEST_CAMERA) {
ImageCropFunction();
}
else if (requestCode == AppConstants.SELECT_FILE) {
if (data != null) {
String path = data.getDataString();
uri = Uri.parse(path);
Bitmap photo = null;
try {
photo = MediaStore.Images.Media.getBitmap(this.getContentResolver(),uri);
} catch (IOException e) {
e.printStackTrace();
}
//External sdcard location
File sdCardDirectory = new File(Environment.getExternalStorageDirectory(),
"MyFolder/Media/Profile");
sdCardDirectory.mkdirs();
File finalimage = new File(sdCardDirectory, "tempProfilepic"+ ".jpg");
boolean success = false;
FileOutputStream outStream;
try {
outStream = new FileOutputStream(finalimage);
photo.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
outStream.flush();
outStream.close();
success = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (success) {
uri = Uri.fromFile(finalimage);
ImageCropFunction();
}
}
}else if (requestCode == AppConstants.CROP_FILE) {
if (data != null) {
fileselected = true;
String path = data.getDataString();
if (path != null){
uri = Uri.parse(path);
}else{
uri = uri;
//Bundle extras = data.getExtras();
//Bitmap selectedBitmap = extras.getParcelable("data");
}
Bitmap bitmap = null;
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(),uri);
} catch (IOException e) {
e.printStackTrace();
}
btnprofilepic.setImageBitmap(bitmap);
File sdCardDirectory = new File(Environment.getExternalStorageDirectory(),
"MyFolder/Media/Profile");
sdCardDirectory.mkdirs();
File finalimage = new File(sdCardDirectory, "Profilepic"+currentDateandTime+ ".jpg");
File tempimage = new File(sdCardDirectory, "tempProfilepic" + ".jpg");
if (tempimage.exists()) {
tempimage.delete();
}
boolean success = false;
FileOutputStream outStream;
try {
outStream = new FileOutputStream(finalimage);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
outStream.flush();
outStream.close();
success = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (success) {
selectedfile = finalimage.toString();
} else {
//app.showToast("Error during image saving");
}
}
}
}
}
public void ImageCropFunction() {
try {
CropIntent = new Intent("com.android.camera.action.CROP");
CropIntent.setDataAndType(uri, "image/*");
CropIntent.putExtra("crop", "true");
CropIntent.putExtra("outputX", 500);
CropIntent.putExtra("outputY", 500);
CropIntent.putExtra("aspectX", 1);
CropIntent.putExtra("aspectY", 1);
CropIntent.putExtra("scale", true);
startActivityForResult(CropIntent, AppConstants.CROP_FILE);
} catch (ActivityNotFoundException e) {
}
}//Image Crop Code End Here
*********************自定义对话框XML文件******************
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/White"
android:gravity="center"
android:orientation="vertical"
android:padding="25dp">
<TextView
android:id="@+id/txtheader"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:layout_marginTop="15dp"
android:text="Select an Image to upload"
android:textColor="@color/Black"
android:textSize="16sp"
android:textStyle="normal" />
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="@color/White" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp">
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center"
android:layout_marginRight="5dp"
android:orientation="vertical">
<Button
android:id="@+id/btncamera"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Take Photo"
android:textColor="@color/White"
android:textSize="14dp" />
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center"
android:layout_marginLeft="5dp"
android:orientation="vertical">
<Button
android:id="@+id/btngallery"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="From Gallery"
android:textColor="@color/White"
android:textSize="14dp" />
</LinearLayout>
</LinearLayout>