MonoDroid Get Full Image Path, OnActivityResult - xamarin.android

Using OnActivityResult, how do I get the full path of an image? I am using OnActivityResult and I get get a Bitmap. Can I load that info a file somehow? Here is my code:
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
try
{
base.OnActivityResult(requestCode, resultCode, data);
switch (requestCode)
{
case REQUEST_IMAGE:
if (resultCode == Result.Ok)
{
//Bitmap thumbnail = (Bitmap)data.Extras.Get("data");
//imagePicture.SetImageBitmap(thumbnail);
}
break;
default:
break;
}
}
catch (System.Exception ex)
{
}
}

You could do something like this to write the image out to a file:
var bitmap = (Android.Graphics.Bitmap)data.Extras.Get("data");
using (var stream = File.Create("/path/to/file"))
{
bitmap.Compress(Android.Graphics.Bitmap.CompressFormat.Png, 0, stream);
}

Related

How to pick the image from gallery, crop the image and the save image as profile image in xamarin android

hello please help me in this regard I want to select pic from gallery and crop the pic and save the pic in some folder
Please help me in this regard
enter code here
private void ProfilePic_Click(object sender, EventArgs e)
{
Intent = new Intent();
Intent.SetType("image/*");
Intent.SetAction(Intent.ActionGetContent);
StartActivityForResult(Intent.CreateChooser(Intent, "EZ-Gift Profile Pic"), PickImageId);
}
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
if ((requestCode == PickImageId) && (resultCode == Result.Ok) && (data != null))
{
Android.Net.Uri uri = data.Data;
//Toast.MakeText(this, path, ToastLength.Long).Show();
Toast.MakeText(this, uri.ToString(), ToastLength.Long).Show();
ProfilePic.SetImageURI(uri);
string path = GetPathToImage(data.Data);
edit = prefs.Edit();
edit.PutString("ProfilePicUri", uri.ToString());
Toast.MakeText(this, uri.ToString(), ToastLength.Long).Show();
Toast.MakeText(this, path, ToastLength.Long).Show();
}
}
private string GetPathToImage(Android.Net.Uri contentURI)
{
ICursor cursor = ContentResolver.Query(contentURI, null, null, null, null);
cursor.MoveToFirst();
string documentId = cursor.GetString(0);
documentId = documentId.Split(':')[1];
cursor.Close();
cursor = ContentResolver.Query(
Android.Provider.MediaStore.Images.Media.ExternalContentUri,
null, MediaStore.Images.Media.InterfaceConsts.Id + " = ? ", new[] { documentId }, null);
cursor.MoveToFirst();
string path = cursor.GetString(cursor.GetColumnIndex(MediaStore.Images.Media.InterfaceConsts.Data));
cursor.Close();
return path;
}
Add the below code to Crop the image.Modify your OnActivityResult code , try like this. Hope this may help you.
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
if ((requestCode == PickImageId) && (resultCode == Result.Ok) && (data != null))
{
Android.Net.Uri uri = data.Data;
//Toast.MakeText(this, path, ToastLength.Long).Show();
Toast.MakeText(this, uri.ToString(), ToastLength.Long).Show();
// It will crop the image accordingly.
cropPicture(uri);
string path = GetPathToImage(data.Data);
Toast.MakeText(this, uri.ToString(), ToastLength.Long).Show();
Toast.MakeText(this, path, ToastLength.Long).Show();
}
else if(requestCode == CROP_PIC)
{
// Get your cropped image here using Bundle and save the bitmap in particular location.
}
}
private void cropPicture(Android.Net.Uri picUri)
{
try
{
// call the standard crop action intent (the user device may not
// support it)
Intent cropIntent = new Intent("com.android.camera.action.CROP");
// indicate image type and Uri
cropIntent.SetDataAndType(picUri, "image/*");
// set crop properties
cropIntent.PutExtra("crop", "true");
// indicate aspect of desired crop
cropIntent.PutExtra("aspectX", 2);
cropIntent.PutExtra("aspectY", 1);
// indicate output X and Y
cropIntent.PutExtra("outputX", 256);
cropIntent.PutExtra("outputY", 256);
// retrieve data on return
cropIntent.PutExtra("return-data", true);
// start the activity - we handle returning in onActivityResult
StartActivityForResult(cropIntent, CROP_PIC);
}
// respond to users whose devices do not support the crop action
catch (ActivityNotFoundException anfe)
{
Toast toast = Toast
.MakeText(this, "This device doesn't support the crop action!", ToastLength.Long);
toast.Show();
}
}

Xamarin ios - referenceUrl from UIImagePickerController always null

I'm selecting an image form the gallery using the UIImagePickerController. After selecting an image, I would like to update the real image file path on a text field.
Can I get the file path from the referenceUrl? The referenceUrl in my case always returns null.
protected void Handle_FinishedPickingMedia (object sender, UIImagePickerMediaPickedEventArgs e)
{
try{
//determine what was selected, video or image
bool isImage = false;
switch(e.Info [UIImagePickerController.MediaType].ToString()) {
case "public.image":
Console.WriteLine("Image selected");
isImage = true;
break;
}
// get common info (shared between images and video)
NSUrl referenceURL = e.Info[new NSString("UIImagePickerControllerReferenceUrl")] as NSUrl;
if (referenceURL != null)
Console.WriteLine("Url:"+referenceURL.ToString ());
// if it was an image, get the other image info
if(isImage) {
// get the original image
UIImage originalImage = e.Info[UIImagePickerController.OriginalImage] as UIImage;
if(originalImage != null) {
// do something with the image
new Thread(new System.Threading.ThreadStart(() => {
Thread.Sleep(350);
BeginInvokeOnMainThread (() => {
var tag = ((UIButton)sender).Tag;
//UIButton senderButton = (UIButton)sender;
switch(tag)
{
case 0:
// do something here
break;
case 1:
// do something here
break;
});
})).Start();
}
}
// dismiss the picker
imagePicker.DismissModalViewController (true);
}catch(Exception ex)
{
ShowAlert ("Failed !", "Unable to select image", "");
Console.WriteLine(ex.Message + ex.StackTrace);
}
}
For anyone else facing this issue, the solution was a simple typo.I printed out the details of the NSDictionary and noticed that the "Url" part of the
UIImagePickerControllerReferenceUrl was all caps. This is what worked for me.
Change this line:
NSUrl referenceURL = e.Info[new NSString("UIImagePickerControllerReferenceUrl")] as NSUrl;
To this :
NSUrl referenceURL = e.Info[new NSString("UIImagePickerControllerReferenceURL")] as NSUrl;
To get the filename of the selected image, I added the AssestsLibrary and used that to extract the necessary metadata.
Here's my full implementation:
protected void Handle_FinishedPickingMedia (object sender, UIImagePickerMediaPickedEventArgs e)
{
try{
//determine what was selected, video or image
bool isImage = false;
switch(e.Info [UIImagePickerController.MediaType].ToString()) {
case "public.image":
Console.WriteLine("Image selected");
isImage = true;
break;
}
// get common info (shared between images and video)
NSUrl referenceURL = e.Info[new NSString("UIImagePickerControllerReferenceURL")] as NSUrl;
if (referenceURL != null)
Console.WriteLine("Url:"+referenceURL.ToString ());
ALAssetsLibrary assetsLibrary = new ALAssetsLibrary();
assetsLibrary.AssetForUrl(referenceURL,delegate (ALAsset asset){
ALAssetRepresentation representation = asset.DefaultRepresentation;
if (representation == null)
{
return;
}else{
string fileName = representation.Filename;
Console.WriteLine("Image Filename :" + fileName);
}
},delegate(NSError error) {
Console.WriteLine ("User denied access to photo Library... {0}", error);
});
// if it was an image, get the other image info
if(isImage) {
// get the original image
UIImage originalImage = e.Info[UIImagePickerController.OriginalImage] as UIImage;
if(originalImage != null) {
// do something with the image
new Thread(new System.Threading.ThreadStart(() => {
Thread.Sleep(350);
BeginInvokeOnMainThread (() => {
var tag = ((UIButton)sender).Tag;
//UIButton senderButton = (UIButton)sender;
switch(tag)
{
case 0:
// do something here
break;
case 1:
// do something here
break;
});
})).Start();
}
}
// dismiss the picker
imagePicker.DismissModalViewController (true);
}catch(Exception ex)
{
ShowAlert ("Failed !", "Unable to select image", "");
Console.WriteLine(ex.Message + ex.StackTrace);
}
}

Illegal Argument Exception when trying to convert byte to Bitmap in blackberry

Here is my code where i am getting profile image bytes from twitter api,
new Thread() {
public void run() {
byte dbata[] = getBitmap(profle_pic_str);
if (dbata != null) {
EncodedImage bitmap_img = EncodedImage.createEncodedImage(dbata, 0, -1);
Bitmap image =bitmap_img.getBitmap();
final Bitmap profle_pic_bmp = image;
final Bitmap scld_bmp = new Bitmap(90, 100);
Application.getApplication().invokeLater(new Runnable() {
public void run() {
if (profle_pic_bmp != null) {
profle_pic_bmp.scaleInto(scld_bmp, Bitmap.FILTER_LANCZOS);
phot_profle.setBitmap(scld_bmp);
} else {
Dialog.alert("null");
}
}
});
// } else {
// Dialog.alert("bytes are null");
}
}
}.start();
Here i have method getBitmap(profle_pic_str); which returning bytes array of image,
public byte[] getBitmap(String url) {
Bitmap bitmap = null;
String strg = HttpConnector.getConnectionString();
byte b[] = null;
try {
b = getXML(url + strg);
} catch (IOException ie) {
ie.printStackTrace();
}
return b;
}
the url which i used is this one
http://api.twitter.com/1/users/profile_image?screen_name=screen_nameof_user&size=bigger
public byte[] getXML(String url) throws IOException {
ContentConnection connection =
(ContentConnection) javax.microedition.io.Connector.open(url);
java.io.DataInputStream iStrm = connection.openDataInputStream();
java.io.ByteArrayOutputStream bStrm = null;
byte xmlData[] = null;
try {
// ContentConnection includes a length method
int length = (int) connection.getLength();
if (length != -1) {
xmlData = new byte[length];
// Read the png into an array
// iStrm.read(imageData);
iStrm.readFully(xmlData);
} else // Length not available...
{
bStrm = new java.io.ByteArrayOutputStream();
int ch;
while ((ch = iStrm.read()) != -1) bStrm.write(ch);
xmlData = bStrm.toByteArray();
bStrm.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// Clean up
if (iStrm != null) iStrm.close();
if (connection != null) connection.close();
if (bStrm != null) bStrm.close();
}
return xmlData;
}
When i am trying to convert byte array to EncodedImage
EncodedImage bitmap_img = EncodedImage.createEncodedImage(dbata, 0, -1);
in this line of code i am getting illegal argument exception.
same code is working for Facebook profile image. I dont know why this code giving error when i am doing for twitter. Please help me friends.
try this -
EncodedImage _encoded_img = EncodedImage.createEncodedImage(dbata, 0, dbata.length);
On your code,
EncodedImage bitmap_img = EncodedImage.createEncodedImage(dbata, 0,-1);
-1 is the length of the array. Its not static. Change -1 to dbata.length.

How to load an image in Dart

I'm trying out the Dart Language and HTML5 Canvas element, but I'm stuck with one problem. I don't know how to load an image in Dart. I can get CanvasRenderingContext2D and with this I can call fillText() and fillRect() and everything works, but I am trying to figure out how to load an Image and draw with drawImage.
Create and load the image
ImageElement image = new ImageElement(src: "my_image.png");
image.onLoad.listen((e) {
// Draw once the image is loaded
});
Draw the above image on the canvas after it is loaded
context.drawImage(image, destX, destY);
Newer image onload syntax:
readFile() {
ImageElement image = new ImageElement(src: "plant.png");
document.body.nodes.add(image);
image.onLoad.listen(onData, onError: onError, onDone: onDone, cancelOnError: true);
}
onData(Event e) {
print("success: ");
}
onError(Event e) {
print("error: $e");
}
onDone() {
print("done");
}
This is another way to do it :
void main() {
ImageElement image = new ImageElement(src: "pic.png");
img.onLoad.listen(onData);
img.onError.listen(onError);
}
void onData(Event e) {
print("Load success");
}
void onError(Event e) {
print("Error: $e");
}

Canon EDSDK ObjectEvent_DirItemRequestTransfer

My C# application is shooting an image every 3 minutes and I get the image from the EDSDK as expected every time. My problem is that the application is leaking about 5 mb for every shot and Iøm very sure that the problem is the EDSDK.
Code:
private uint CameraObjectEvent(uint inEvent, IntPtr inRef, IntPtr inContext)
{
switch (inEvent)
{
case EDSDK.ObjectEvent_DirItemRequestTransfer:
GetCapturedItem(inRef);
break;
}
return EDSDKErrorCodes.EDS_ERR_OK;
}
private void GetCapturedItem(IntPtr directoryItem)
{
uint error = EDSDKErrorCodes.EDS_ERR_OK;
IntPtr stream = IntPtr.Zero;
//Get information of the directory item.
EDSDK.EdsDirectoryItemInfo dirItemInfo;
error = EDSDK.EdsGetDirectoryItemInfo(directoryItem, out dirItemInfo);
if (error != EDSDKErrorCodes.EDS_ERR_OK)
{
OnCameraErrorRaised(error, "EDSDK.EdsGetDirectoryItemInfo failed.");
return;
}
//Create a file stream for receiving image.
error = EDSDK.EdsCreateMemoryStream(dirItemInfo.Size, out stream);
if (error != EDSDKErrorCodes.EDS_ERR_OK)
{
OnCameraErrorRaised(error, "EDSDK.EdsCreateMemoryStream failed");
return;
}
//Fill the stream with the resulting image
error = EDSDK.EdsDownload(directoryItem, dirItemInfo.Size, stream);
if (error != EDSDKErrorCodes.EDS_ERR_OK)
{
OnCameraErrorRaised(error, "EDSDK.EdsDownload failed.");
return;
}
error = EDSDK.EdsDownloadComplete(directoryItem);
if (error != EDSDKErrorCodes.EDS_ERR_OK)
{
OnCameraErrorRaised(error, "EDSDK.EdsDownloadComplete failed.");
return;
}
//Copy the stream to a byte[]
IntPtr pointerToBytes = IntPtr.Zero;
EDSDK.EdsGetPointer(stream, out pointerToBytes);
MemoryStream imageStream = null;
Image image = null;
try
{
byte[] buffer = new byte[dirItemInfo.Size];
GCHandle gcHandle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
Marshal.Copy(pointerToBytes, buffer, 0, (int)dirItemInfo.Size);
//Create a MemoryStream and return the image
imageStream = new MemoryStream(buffer);
image = Image.FromStream(imageStream);
}
catch (Exception ex)
{
OnCameraErrorRaised(999999, string.Format("Failed while retrieving image from camera. Exception: {0}.", ex.Message));
}
finally
{
if (imageStream != null)
imageStream.Dispose();
}
//If image was captured then send ImageCaptured event
if (image != null)
OnImageCaptured(image);
//Clean up
EDSDK.EdsRelease(pointerToBytes);
pointerToBytes = IntPtr.Zero;
EDSDK.EdsRelease(stream);
stream = IntPtr.Zero;
EDSDK.EdsRelease(directoryItem);
directoryItem = IntPtr.Zero;
}
The line OnImageCaptured(image) just sends the image to a controller which merges the image from the camera with another image and then disposes both images after saving the finale merged image:
private void ImageCaptured(Image originalImage)
{
Image watermark = null;
//Merge images
try
{
watermark = Image.FromFile(Settings.Default.ImageWatermarkFilename);
_imageController.Merge(originalImage, watermark);
_imageController.SaveImage(originalImage);
}
catch (Exception ex)
{
LogManager.Instance.UpdateLog(string.Format("Error - Failed to merge and save images. Exception: {0}.", ex.Message));
//HACK:
System.Windows.Forms.Application.Restart();
App.Current.Shutdown();
}
finally
{
originalImage.Dispose();
if (watermark != null)
watermark.Dispose();
}
}
So why does the app memory leak - any ideas?
/Cheers
release your GCHandle. it is the culprit eating memory every time when you are taking shoot
gcHandle.Free()

Resources