I am creating a UWP app for the company I work for part of the process is to upload an ID Photo. When the user clicks to upload a picker displays and it loads the image to an Image Element. This works fine, the issue is when the pull an existing record that has a photo attached already. The file is stored as a byte[], the code I use on .Net web apps does not work here. I can not get it to work even after a week of reading post after post on countless sites.
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
photo.ID = reader.GetGuid(0);
photo.AttachmentType = reader.GetString(1);
photo.AttachmentSize = reader.GetInt32(2);
photo.Attachment = (byte[])reader.GetValue(3);
}
}
RemoveBtn.Visibility = Visibility.Visible;
}
}
}
}
}
catch (Exception eSql)
{
var err = eSql.Message.ToString();
}
if (photo.Attachment != null && photo.Attachment.Length > 0)
{
//StorageFolder folder = Windows.ApplicationModel.Package.Current.InstalledLocation;
//StorageFile file = await folder.CreateFileAsync($"tempImg{photo.AttachmentType}");
//string path = #"D:\DOT2";
//string fileName = "tempImg.png";
//string pathStr = Path.Combine(path, fileName);
using (Stream stream = new MemoryStream())
{
await stream.WriteAsync(photo.Attachment, 0, photo.Attachment.Length);
using (IRandomAccessStream fileStream = stream.AsRandomAccessStream())
{
BitmapImage img = new BitmapImage();
await img.SetSourceAsync(fileStream); //Error Occurs here.
CIPhoto.Source = img;
}
}
UploadBtn.Visibility = Visibility.Collapsed;
RemoveBtn.Visibility = Visibility.Visible;
}
The expected result is to convert the byte[] to a BitmapImageSource that i can set to an Image UI Element. I get error after error, currently i get an error saying : 'Attempted to read or write protected memory. This is often an indication that other memory is corrupt.'. The commented section tells me that i am denied access. I am stuck, please help.
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.
My goal is to take an embedded image which is saved in each project's image folder, stream it, convert it to a byte array and save it to the device's local storage file system using PCLStorage. The part which I cannot figure out is how to stream from the embedded image.
var embeddedImage = new Image { Aspect = Aspect.AspectFit };
embeddedImage.Source = ImageSource.FromResource("applicationIcon.png");
then I could stream it if I had the path, or I could convert it to a byte [] if I had a stream. The code below does not work because the file source is not found (obviously).
string localFileUri = string.Empty;
// Get hold of the file system.
IFolder localFolder = FileSystem.Current.LocalStorage;
IFile file = await FileSystem.Current.GetFileFromPathAsync("applicationIcon.png");
using (Stream stream = await file.OpenAsync(FileAccess.Read))
{
using (var ms = new MemoryStream())
{
var byteArray = ms.ToArray();
var storeragePath = await iStorageService.SaveBinaryObjectToStorageAsync(string.Format(FileNames.ApplicationIcon, app.ApplicationId), byteArray);
app.IconURLLocal = storeragePath;
}
}
The only option seems to be to use some kind of resource locator, and then maintain that code for each type of project you add. Not very elegant. Is there another way?
First off, thank you to deckertron_9000 for putting me on the right path to figuring it out, and secondly these two links:
http://www.itgo.me/a/3956119637998661919/xamarin-forms-how-to-load-an-image-from-resources-into-a-byte-array
Xamarin Forms: How to use Embedded Resources in PCL Project for Image
In the end, this is what worked for me:
Firstly I added the image to a folder in my PCL. Then I made sure to change the image's Build Action to Embedded Resource.
Secondly, I added using System.Reflection;
Thirdly, this code worked for me:
string imagePath = "NameOfProject.Assets.applicationIcon.png";
Assembly assembly = typeof(NameOfClass).GetTypeInfo().Assembly;
byte[] buffer;
using (Stream stream = assembly.GetManifestResourceStream(imagePath))
{
long length = stream.Length;
buffer = new byte[length];
stream.Read(buffer, 0, (int)length);
var storeragePath = await iStorageService.SaveBinaryObjectToStorageAsync(string.Format(FileNames.ApplicationIcon, app.ApplicationId), buffer);
app.IconURLLocal = storeragePath;
}
if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
{
await App.CurrentApp.MainPage.DisplayAlert("No Camera", ":( No camera available.", "OK");
return;
}
_mediaFile = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions
{
Directory = "Sample",
Name = "test.jpg"
});
if (_mediaFile == null)
return;
//ViewModel.StoreImageUrl(file.Path);
await App.CurrentApp.MainPage.DisplayAlert("Snap", "Your photo have been added to your Items collection.", "OK");
ImageSource = ImageSource.FromStream(() =>
{
var stream = _mediaFile.GetStream();
_mediaFile.Dispose();
return stream;
});
I need to get Thumbnail from mp3 files. I Implemented this but it never catch thumbnails. I checked the existence of the images opening them with windows media player and from xbox music (on the phone) but i can't retrieve them in my app. Please Help
async private void ThumbnailFetcher(StorageFile file)
{
if (file != null)
{
const ThumbnailMode thumbnailMode = ThumbnailMode.MusicView;
const uint size = 100;
using (StorageItemThumbnail thumbnail = await file.GetThumbnailAsync(thumbnailMode, size))
{
if (thumbnail != null && thumbnail.Type == ThumbnailType.Image)
{
this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
BitmapImage thumbnailImage = new BitmapImage();//image used for display
thumbnailImage.SetSource(thumbnail);
CurrentAlbumArt.Source = thumbnailImage;
Debug.WriteLine("true");
});
}
else
{
Debug.WriteLine("False");
}
}
}
}
P.s It gives always false.
It seems there is a bug on windows phone 8.1, I searched all the night and the only method I could implemented is this
var fileStream = await file.OpenStreamForReadAsync();
var TagFile = File.Create(new StreamFileAbstraction(file.Name, fileStream, fileStream));
// Load you image data in MemoryStream
var tags = TagFile.GetTag(TagTypes.Id3v2);
IPicture pic = TagFile.Tag.Pictures[0];
MemoryStream ms = new MemoryStream(pic.Data.Data);
ms.Seek(0, SeekOrigin.Begin);
bitmap.SetSource(ms.AsRandomAccessStream());
AlbumArt.Source = bitmap;
but it doesn't work too..
var filestream = await receivedFile.OpenStreamForReadAsync();
var tagFile = File.Create(new StreamFileAbstraction(receivedFile.Name, filestream, filestream));
var tags = tagFile.GetTag(TagLib.TagTypes.Id3v2);
var bin = (byte[])(tags.Pictures[0].Data.Data);
MemoryStream ms = new MemoryStream(bin);
await bitmapImage.SetSourceAsync(ms.AsRandomAccessStream());
AlbumArt.Source=bitmapImage;
use this and taglib portable. (Sorry for take so much time)
I'm trying to save a file to the Documents folder using PickSaveFileAndContinue() method in WP 8.1 RT. Everything is happening fine except the file which gets saved is empty.
When I get the file returned from the following code in OnActivated() method, it's size is zero.
Anyone?
var database = await FileHelper.GetFileAsync(ApplicationData.Current.LocalFolder, DATABASE_NAME);
FileSavePicker savePicker = new FileSavePicker();
savePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
savePicker.FileTypeChoices.Add("Database File", new List<string>() { ".db" });
savePicker.DefaultFileExtension = ".db";
savePicker.SuggestedFileName = DATABASE_NAME;
savePicker.SuggestedSaveFile = database;
After the location is picked, the following code is executed in App.xaml.cs. I tried doing this inside the same page using a ContinuationManager. But then result is same.
protected async override void OnActivated(IActivatedEventArgs args)
{
byte[] buffer = null;
if(args!=null)
{
if(args.Kind == ActivationKind.PickSaveFileContinuation)
{
var file = ((FileSavePickerContinuationEventArgs)args).File;//This is empty
using (IRandomAccessStreamWithContentType stream = await file.OpenReadAsync())
{
buffer = new byte[stream.Size];
using (DataReader reader = new DataReader(stream))
{
await reader.LoadAsync((uint)stream.Size);
reader.ReadBytes(buffer);
}
}
if (file != null)
{
CachedFileManager.DeferUpdates(file);
await FileIO.WriteBytesAsync(file, buffer);
Windows.Storage.Provider.FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(file);
}
}
}
base.OnActivated(args);
}
That's expected. PickSaveFileAndContinue doesn't know what the app wants to save. It just provides an empty StorageFile. The app can then write whatever contents it wants to save into the file.
How do I solve the exception, Operation not permitted on IsolatedFileStream?
After debugging, I realised that a certain line wasn't read and it was skipped to the catch part. I am reading images from the photo samples in windows phone 7 as well as uploading them into skydrive. Can anybody guide me on how to solve this problem asap?
Thanks.
public BitmapImage fileName { get; set; }
private void GetImages()
{
MediaLibrary mediaLibrary = new MediaLibrary();
var pictures = mediaLibrary.Pictures;
foreach (var picture in pictures)
{
BitmapImage image = new BitmapImage();
image.SetSource(picture.GetImage());
MediaImage mediaImage = new MediaImage();
mediaImage.fileName = image;
UploadFile(mediaImage, picture.Name);
}
}
public void UploadFile(MediaImage image, string filepath)
{
if (skyDriveFolderID != string.Empty)
{
this.client.UploadCompleted += new EventHandler<LiveOperationCompletedEventArgs>(ISFile_UploadCompleted);
infoTextBlock.Text = "Uploading backup...";
dateTextBlock.Text = "";
try
{
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
// error occurs HERE
IsolatedStorageFileStream readStream = myIsolatedStorage.OpenFile(filepath, FileMode.Open, FileAccess.Read);
readStream.Close();
this.client.UploadAsync(skyDriveFolderID, filepath, true, readStream, null)
}
}
Are you sure error occurs there? I can se you are closing the stream before reading it. So it may be that you got the line of error wrong.
Also, are you absolutely sure, that file with that exact name exists in Isolated Storage?