保存图片并在图像视图中加载
Posted
技术标签:
【中文标题】保存图片并在图像视图中加载【英文标题】:Saving picture and loading in an imageview 【发布时间】:2014-02-23 22:14:44 【问题描述】:如果我拍照,它会显示在图像视图中。这很好用。但是如何将照片额外保存在硬盘上?拿他相机设置的大小?
public class Note extends Activity
TextView t;
ImageView iv;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.note);
iv=(ImageView) findViewById(R.id.imageView);
Button btn = (Button) findViewById(R.id.photo);
btn.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View view)
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 0);
);
public void button (View view)
Intent intent = new Intent(view.getContext(),Note2.class);
startActivityForResult(intent, 0);
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
if(requestCode==0)
Bitmap theImage = (Bitmap) data.getExtras().get("data");
iv.setImageBitmap(theImage);
提前感谢您的帮助。
【问题讨论】:
【参考方案1】:制作 uri 和文件
public File mediaFile;
public Uri fileUri;
把这两个方法放到你的文件里
/** Create a file Uri for saving an image or video */
private static Uri getOutputMediaFileUri(int type)
return Uri.fromFile(getOutputMediaFile(type));
/** Create a File for saving an image or video */
private static File getOutputMediaFile(int type)
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "YourFolderName");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists())
if (! mediaStorageDir.mkdirs())
Toast.makeText(null, "failed to create directory", Toast.LENGTH_SHORT).show();
return null;
if (type == 1)
Long tsLong = System.currentTimeMillis()/1000;
String ts = tsLong.toString();
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"photo"+ ts + ".jpg");
else
return null;
return mediaFile;
然后在你开始之前ActivityForResult(intent, 0);放:
fileUri = getOutputMediaFileUri(1);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
intent.putExtra("return-data", true);
确保在清单中输入:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
【讨论】:
以上是关于保存图片并在图像视图中加载的主要内容,如果未能解决你的问题,请参考以下文章