I'm using Xamarin for Android. I load an image and put it in ImageView, then I edit the image. Next I want to save that image to SD card.
Anyone know how to save the image into SD card because I only can find it in Java Android. I already try to convert the code from Java to C# but still get an error.
Any help, thanks in advance.
I get an error at InputStream iS = Resources.OpenRawResource(Resource.Drawable.Icon); as the error is "cannot implicitly convert type 'System.IO.Stream' to 'Java.IO.InputStream'"
Here's the code:
Java.IO.File path = Android.OS.Environment.GetExternalStoragePublicDirectory (Android.OS.Environment.DirectoryPictures);
Java.IO.File file = new Java.IO.File (path, "Icon.png");
try {
path.Mkdirs();
InputStream iS = Resources.OpenRawResource(Resource.Drawable.Icon);
OutputStream oS = new FileOutputStream(file);
byte[] data = new byte[iS.Available()];
iS.Read(data);
oS.Write(data);
iS.Close();
oS.Close();
} catch (Exception ex) {
// ...
}
I use this to save the captured photo to sdcard:
public void OnPictureTaken(byte[] data, Android.Hardware.Camera camera)
{
// Save the image JPEG data to the SD card
FileOutputStream outStream = null;
File dataDir = Android.OS.Environment.ExternalStorageDirectory;
if (data!=null)
{
try
{
outStream = new FileOutputStream(dataDir + "/" + PICTURE_FILENAME);
outStream.Write(data);
outStream.Close();
}
catch (FileNotFoundException e)
{
Android.Util.Log.Debug("SIMPLECAMERA", e.Message);
}
catch (IOException e)
{
Android.Util.Log.Debug("SIMPLECAMERA", e.Message);
}
File file = new File(dataDir + "/" + PICTURE_FILENAME);
try
{
ExifInterface exif = new ExifInterface(file.CanonicalPath);
// Read the camera model and location attributes
exif.GetAttribute(ExifInterface.TagModel);
float[] latLng = new float[2];
exif.GetLatLong(latLng);
// Set the camera make
exif.SetAttribute(ExifInterface.TagMake, “My Phone”);
exif.SetAttribute(ExifInterface.TagDatetime,
System.DateTime.Now.ToString());
}
catch (IOException e) {
Android.Util.Log.Debug("SIMPLECAMERA", e.Message);
}
}
else
{
Toast.MakeText(this, "No Image Captured", ToastLength.Long);
}
}
found the answer, credit to Mohd Riyaz.
var yourImageView = new ImageView(this); //Your image view
var fetchedDrawable = yourImageView.Drawable;
BitmapDrawable bitmapDrawable = (BitmapDrawable)fetchedDrawable;
var bitmap = bitmapDrawable.Bitmap;
using (var stream = new FileStream("AbsolutePath_File", FileMode.Create))
{
bitmap.Compress(Bitmap.CompressFormat.Jpeg, 100, stream);
}
Related
var getImage = model.Document.Get().Where(x => x.ReferenceNo == ReferenceNo && x.ChecklistId == 225).FirstOrDefault();
var Imagefilename = path + "\\" + ReferenceNo.Replace("/", "_") + "IdentityPhoto.Jpg";
var filebytes = ConvertToBytes(getImage.FileData);
using (var filestream = new FileStream(Imagefilename, FileMode.Create, FileAccess.Write))
{
filestream.Write(filebytes, 0, filebytes.Length);
filestream.Close();
filestream.Dispose();
}
using (Spire.Doc.Document document = new Spire.Doc.Document(#OpenTemplate))
{
Spire.Doc.Section section = document.Sections[0];
System.Drawing.Bitmap p = new Bitmap(System.Drawing.Image.FromFile(#Imagefilename));
// p.RotateFlip(RotateFlipType.Rotate90FlipX);
Spire.Doc.Fields.DocPicture picture = document.Sections[0].Paragraphs[0].AppendPicture(p);
// set image's position
picture.HorizontalPosition = 370.0F;
picture.VerticalPosition = 480.0F;
// set image's size
picture.Width = 80;
picture.Height = 80;
// set textWrappingStyle with image;
picture.TextWrappingStyle = Spire.Doc.Documents.TextWrappingStyle.Through;
// Save doc file.
document.SaveToFile(#Demo, Spire.Doc.FileFormat.Docx);
p.Dispose();
document.Dispose();
document.Close();
}
// Trying to delete this file
try
{
if (File.Exists(Imagefilename))
{
File.Delete(Imagefilename);
}
}
catch (Exception exception)
{
Console.WriteLine(exception);
}
Using a Word document as template, image is retrieved from database. It is stored on the C drive, the image at that location is then being used and inserted into a word document.
When trying to delete the image from the drive after use it keeps on throwing an error:
Error message "process cannot access the file because it is being used by another process"
I have tried using .Dispose and .Close functions and using statements. I have tried Directory.Delete but nothing seems to be working.
I have a camerapage which takes a picture, resizes it to a thumbnail and saves this resized image to a file locally on the android phone. I then try to send this uri-string to a viewmodel which is supposed to set its ImageSource property from this uri. I am currently unable to load the image from the url.
Here is my code:
In CameraPage(inside Take photo method)
var documentsPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
using (var imageStream = new MemoryStream())
{
await image.CompressAsync(Bitmap.CompressFormat.Jpeg, 40, imageStream);
image.Recycle();
imageBytes = imageStream.ToArray();
var thumbnail =await DependencyService.Get<IPicResizer>().GetResizedImage(imageBytes);
// Temporary file to store the downloaded image
Java.IO.File tmpFile = new Java.IO.File(documentsPath + "/"+fileName + ".jpg");
tmpFile.ParentFile.Mkdirs();
// String path = MediaStore.Images.Media.InsertImage(this.Context.ContentResolver, documentsPath, fileName, ""); //(this.Context.ContentResolver, image, imgName.ToString(), null);
uri = Android.Net.Uri.Parse(tmpFile.Path);
// The FileOutputStream to the temporary file
var fOutStream = new FileOutputStream(tmpFile);
try
{
fOutStream.Write(thumbnail, 0, thumbnail.Length);
fOutStream.Flush();
fOutStream.Close();
DialogService.HideLoading();
DialogService.ShowSuccess("Saved picture at: " + uri.ToString());
}
catch (Java.IO.FileNotFoundException ex)
{
DialogService.ShowError(ex.InnerException.Message);
}
catch (Java.IO.IOException ex)
{
DialogService.ShowError(ex.InnerException.Message);
}
camera.StartPreview();
await App.Current.MainPage.Navigation.PushModalAsync(new InfoPage(imageBytes, tmpFile.AbsolutePath), false);
}
InfoPages view model:
ImageSource Source {get;set;}
public InfoViewModel(byte[] image, string imageUri)
{
if (image != null)
{
_image = image;
imageurl = new Uri("file:///" + imageUri, UriKind.Absolute);
Source = ImageSource.FromUri(imageurl);
}
}
All help is appreciated :)
I want to be able to save images in IsolatedStorage, and later get it.
for this purpose I wrote a helper which I want to access it from everywhere in my app:
for creating an image:
public static void SaveImage(Stream image, string name)
{
try
{
IsolatedStorageFile isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
if (!isolatedStorage.DirectoryExists("MyImages"))
{
isolatedStorage.CreateDirectory("MyImages");
}
var filePath = Path.Combine("MyImages", name + ".jpg");
using (IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(filePath, FileMode.Create, isolatedStorage))
{
StreamWriter sw = new StreamWriter(fileStream);
sw.Write(image);
sw.Close();
}
}
catch (Exception ex)
{
throw new Exception("failed");
}
}
and for getting that image again:
public static BitmapImage Get(string name)
{
try
{
IsolatedStorageFile isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
var filePath = Path.Combine("MyImages", name + ".jpg");
using (IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(filePath, FileMode.Open, isolatedStorage))
{
BitmapImage image = new BitmapImage();
image.SetSource(fileStream);
return image;
}
}
catch (Exception ex)
{
throw new Exception("failed");
}
}
The problem appears when I try to set source of image I get this error message:
The component cannot be found. (Exception from HRESULT: 0x88982F50)
Assuming you have the right Capabilities under your WMAppManifest.xml what you need is:
public static void SaveImage(Stream image, string name)
{
var bitmap = new BitmapImage();
bitmap.SetSource(attachmentStream);
var wb = new WriteableBitmap(bitmap);
var temp = new MemoryStream();
wb.SaveJpeg(temp, wb.PixelWidth, wb.PixelHeight, 0, 50);
using (var myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!myIsolatedStorage.DirectoryExists("MyImages"))
{
myIsolatedStorage.CreateDirectory("MyImages");
}
var filePath = Path.Combine("MyImages", name + ".jpg");
using (IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(filePath, FileMode.Create, myIsolatedStorage))
{
fileStream.Write(((MemoryStream)temp).ToArray(), 0, ((MemoryStream)temp).ToArray().Length);
fileStream.Close();
}
}
}
That should work and store your image as a jpeg into your desired directory. if it doesn't, make sure that the create directory and Path.Combine() methods are being used correctly.
I want to upload my recorded file to skydrive and I am using these codes
For recording;
void StopRecording()
{
// Get the last partial buffer
int sampleSize = microphone.GetSampleSizeInBytes(microphone.BufferDuration);
byte[] extraBuffer = new byte[sampleSize];
int extraBytes = microphone.GetData(extraBuffer);
// Stop recording
microphone.Stop();
// Create MemoInfo object and add at top of collection
int totalSize = memoBufferCollection.Count * sampleSize + extraBytes;
TimeSpan duration = microphone.GetSampleDuration(totalSize);
MemoInfo memoInfo = new MemoInfo(DateTime.UtcNow, totalSize, duration);
memoFiles.Insert(0, memoInfo);
// Save data in isolated storage
using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream stream = storage.CreateFile("/shared/transfers/" + memoInfo.FileName))
{
// Write buffers from collection
foreach (byte[] buffer in memoBufferCollection)
stream.Write(buffer, 0, buffer.Length);
// Write partial buffer
stream.Write(extraBuffer, 0, extraBytes);
}
}
}
For Uploading file;
async void OnSaveButtonClick(object sender, RoutedEventArgs args)
{
Button btn = sender as Button;
MemoInfo clickedMemoInfo = btn.Tag as MemoInfo;
memosListBox.SelectedItem = clickedMemoInfo;
if (this.client == null)
{
gridSingin.Visibility = Visibility.Visible;
memosListBox.Visibility = Visibility.Collapsed;
}
else
{
using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
{
using (var fileStream = store.OpenFile(clickedMemoInfo.FileName, FileMode.Open, FileAccess.Read, FileShare.Read))
{
LiveOperationResult res = await client.BackgroundUploadAsync("me/skydrive",
new Uri("/shared/transfers/" + clickedMemoInfo.FileName, UriKind.Relative),
OverwriteOption.Overwrite
);
InfoText.Text = "File " + clickedMemoInfo.FileName + " uploaded";
}
}
}
}
But I am gettin error in here
LiveOperationResult res = await client.BackgroundUploadAsync("me/skydrive", new Uri("/shared/transfers/" + clickedMemoInfo.FileName, UriKind.Relative), OverwriteOption.Overwrite);
I am getting this error;
An unhandled exception of type 'System.Reflection.TargetInvocationException' occurred in System.Windows.ni.dll
Could you help me, please?
You cannot have the file open when trying to upload. Try doing this.
using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
{
if (store.FileExists(fileName))
{
client.BackgroundUploadAsync("me/skydrive", new Uri(fileName, UriKind.Relative),
OverwriteOption.Overwrite);
}
}
How can I build video from stream image (only image without sound) in C#?
Here is some code of my application:
static int ii = 1;
public void drawBitmap(byte[] data)
{
MemoryStream ms = new MemoryStream(data);
try
{
Bitmap b = new Bitmap(ms);
b.Save(#"c:\test\" + (ii++) + ".jpg");
Image i = (Image)b;
pictureBox1.Image = i;
ii++;
}
catch (Exception e)
{
}
}
I used the wrapper mentioned above, like this:
private static void hejHopp()
{
//http://www.codeproject.com/Articles/7388/A-Simple-C-Wrapper-for-the-AviFile-Library
//myReadyNAS device, got files via FTP from my webcam
var jpgFileList = Directory.EnumerateFiles(sourcePath,"*.jpg");
//load the first image
Bitmap bitmap = (Bitmap)Image.FromFile(jpgFileList.First());
//create a new AVI file
AviManager aviManager = new AviManager(sourcePath + "\\tada.avi", false);
//add a new video stream and one frame to the new file
//set IsCompressed = false
VideoStream aviStream = aviManager.AddVideoStream(false, 2, bitmap);
jpgFileList.Skip(1).ToList().ForEach(file =>
{
bitmap = (Bitmap)Bitmap.FromFile(file);
aviStream.AddFrame(bitmap);
bitmap.Dispose();
});
aviManager.Close();
}
You might want to take a look at this thread:
http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/f23caf50-85a9-4074-8328-176c8bcc393e/
Same question. Some answers.
More is also available here:
http://www.codeproject.com/Articles/7388/A-Simple-C-Wrapper-for-the-AviFile-Library