路径转换为Bitmap
private Bitmap GetBitmap(string path)
{
Bitmap bitmap = null;
FileStream fs = null;
BufferedStream bs = null;
try
{
BitmapFactory.Options options = new BitmapFactory.Options();
options.InJustDecodeBounds = false;
options.InPurgeable = true;
options.InDither = false;
options.InPreferredConfig = Bitmap.Config.Rgb565;
fs = new FileStream(path, FileMode.Open);
bs = new BufferedStream(fs);
bitmap = BitmapFactory.DecodeStream(bs, null, options);
}
finally
{
if (bs != null)
{
bs.Close();
}
if (fs != null)
{
fs.Close();
}
}
return bitmap;
}
拍照
string imgDirStr = System.IO.Path.Combine(Utils.SDCardPath,
Settings.PhotoPath); //存放照片的文件夹
m_ImageName = DateTime.Now.ToString("yyyyMMddHHmmss") + ".jpg";//照片命名
Java.IO.File imgDir = new Java.IO.File(imgDirStr);
if (imgDir.Exists() != true)
{
imgDir.Mkdir();
}
Java.IO.File imgFile = new Java.IO.File(imgDir, m_ImageName);
string m_ImagePath = System.IO.Path.Combine(imgDirStr, m_ImageName);
Android.Net.Uri imgUri = Android.Net.Uri.FromFile(imgFile);
Intent imageCaptureIntent = new Intent(MediaStore.ActionImageCapture);
imageCaptureIntent.PutExtra(MediaStore.ExtraOutput, imgUri);
imageCaptureIntent.PutExtra(MediaStore.ExtraVideoQuality, 1);
StartActivityForResult(imageCaptureIntent, RESULT_CAPTURE_IMAGE);
获取本地照片
var imageIntent = new Intent();
imageIntent.SetType("image/*");
imageIntent.SetAction(Intent.ActionGetContent);
StartActivityForResult(
Intent.CreateChooser(imageIntent, "选择图片"), RESULT_LOAD_LOCALIMAGE);
回调函数
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
try
{
base.OnActivityResult(requestCode, resultCode, data);
if (resultCode == Result.Ok)
{
switch (requestCode)
{
case RESULT_CAPTURE_IMAGE:
string path = GetPath(m_ImageName);
SaveBugAttachment(path, m_ImageName);
RefreshAdapter();
break;
case RESULT_LOAD_LOCALIMAGE:
Android.Net.Uri uri = data.Data;
SaveBugAttachment(uri);
RefreshAdapter();
break;
}
}
}
}
获取路径
private string GetPath(string name)
{
string path = System.IO.Path.Combine(Utils.SDCardPath,
Settings.PhotoPath) + "/" + name;
return path;
}
private void SaveBugAttachment(Android.Net.Uri uri)
{
string name = DateTime.Now.ToString("yyyyMMddHHmmss") + ".jpg";
byte[] data = GetImageData(uri);
SavePhoto(data, name);
string path = GetPath(name);
SaveBugAttachment(path, name);
}
/// <summary>
/// 获取照片数据
/// </summary>
/// <param name="uri"></param>
/// <returns></returns>
private byte[] GetImageData(Android.Net.Uri uri)
{
ContentResolver cr = this.ContentResolver;
Bitmap bitmap = BitmapFactory.DecodeStream(cr.OpenInputStream(uri));
MemoryStream stream = new MemoryStream();
bitmap.Compress(Bitmap.CompressFormat.Jpeg, 50, stream);
byte[] data = stream.ToArray();
return data;
}