Converting an Image to Byte Array in Windows Store App - c#

In WindowsStoreApps i want to convert an Local Image from solution explorer to byte array and then to base64 string.please guide me.The code I have tried so far is as below.
public async Task<string> ToBase64()
{
Byte[] ByteResult = null;
string bs64 = null;
if (url != null)
{
HttpClient client = new HttpClient();
ByteResult = await client.GetByteArrayAsync(url);
}
bs64 = Convert.ToBase64String(ByteResult);
return bs64;
}

Suppose you want to convert an image named MyImage.png from Assets folder then below code will return the base64 string of that image.
private async Task DoWork()
{
var file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/MyImage.png"));
var b64 = await ConvertStorageFileToBase64String(file);
}
private async Task<string> ConvertStorageFileToBase64String(StorageFile File)
{
var stream = await File.OpenReadAsync();
using (var dataReader = new DataReader(stream))
{
var bytes = new byte[stream.Size];
await dataReader.LoadAsync((uint)stream.Size);
dataReader.ReadBytes(bytes);
return Convert.ToBase64String(bytes);
}
}

Try this piece of code
StorageFile file = <Your File>;
var bytes = new Byte[0];
using (IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.Read))
{
var reader = new DataReader(fileStream.GetInputStreamAt(0));
bytes = new Byte[fileStream.Size];
await reader.LoadAsync((uint)fileStream.Size);
reader.ReadBytes(bytes);
}
string imageInStringFormat = Convert.ToBase64String(bytes);

Related

Blazor download html string as Image

public async Task ExportGraph(string projectName, string html)
{
var bytes = Encoding.Default.GetBytes(html);
using var stream = new MemoryStream(bytes);
stream.Seek(0, SeekOrigin.Begin);
using var streamRef = new DotNetStreamReference(stream: stream);
await JS.InvokeVoidAsync("downloadFileFromStream", $"FazerGraph-{projectName}.jpg", streamRef);
}
I have this method that receives a string containing the html I want to create an image from.
I-m getting this string from this JS method:
function getInnerHTMLElement(element) {
if (element) {
return element.innerHTML;
}
return null;
}
When I download the jpg image and try to open it says:
What I'm doing wrong?
I'm using now html converter like this:
public async Task ExportGraph(string projectName, string html)
{
var converter = new HtmlConverter();
var bytes = converter.FromHtmlString(html);
using var stream = new MemoryStream(bytes);
stream.Seek(0, SeekOrigin.Begin);
using var streamRef = new DotNetStreamReference(stream: stream);
await JS.InvokeVoidAsync("downloadFileFromStream", $"FazerGraph-{projectName}.jpg", streamRef);
}
and the result image I get is this:
What can I do to make it the same look like the html (shown bellow)?

byte[] upload to mysql blob contains no data

I'm trying to upload a byte array to a mysql column type mediumblob. after the upload I see the blob has a size in kilobytes, however, when I download the file and view it in notepad... it's just empty white space.
here's how I am getting my bytes from an image PNG file:
private async void artworkFileBTN_Click(object sender, RoutedEventArgs e)
{
FileOpenPicker openPicker = new FileOpenPicker();
openPicker.ViewMode = PickerViewMode.Thumbnail;
openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
openPicker.FileTypeFilter.Add(".png");
artworkfile = await openPicker.PickSingleFileAsync();
if (artworkfile != null)
{
artworkSet = true;
//var stream = await musicfile.OpenAsync(Windows.Storage.FileAccessMode.Read);
artworkFileBTN.Content = artworkfile.DisplayName;
var stream = await artworkfile.OpenAsync(FileAccessMode.Read);
var streamBytes = await artworkfile.OpenStreamForReadAsync();
var bytes = new byte[(int)streamBytes.Length];
ArtworkRawData =bytes;
}
else
{
//
}
}
can anyone tell me why my array contains only whitespace?
Solved.
byte[] result;
using (Stream streambytes = await artworkfile.OpenStreamForReadAsync())
{
using (var memoryStream = new MemoryStream())
{
streambytes.CopyTo(memoryStream);
result = memoryStream.ToArray();
}
}
ArtworkRawData = result;

Uwp Display Image From Table SQL

I have a function On my wcf service it returns Image as Bytes
I didnt Find any idea on how to display it in my Image Control
How can i Convert Those Bytes to an Image And thanks !
Here is my WCF Function:
public List<Data.Product> Show_P()
{
DataTable Table = new DataTable();
List<Data.Product> MyProductsLIST = new List<Data.Product>();
Table = Sp.SelectData("Show_Products", null);
if (Table.Rows.Count > 0)
for (int i = 0; i < Table.Rows.Count; i++)
{
Data.Product Log = new Data.Product();
Log._ID = Convert.ToInt32(Table.Rows[i]["ID"]);
Log._Name = Table.Rows[i]["Name"].ToString();
Log._Price = Table.Rows[i]["Price"].ToString();
Log._Qte = Table.Rows[i]["Qte"].ToString();
Log._CAT = Convert.ToInt32(Table.Rows[i]["Cat"]);
Log._Vote = Convert.ToInt32(Table.Rows[i]["Vote"]);
Log._Image = (byte[])Table.Rows[i]["Image"];
MyProductsLIST.Add(Log);
}
return MyProductsLIST;
}
And in my uwp :
public static List<Products> Get_Products()
{
MspService.Service1Client Serv = new MspService.Service1Client();
MspService.Product[] Product = Serv.Show_PAsync().Result.Show_PResult;
List<Products> Produc = new List<Design_TesTiNg.MenuBox.Products>();
for (int i = 0; i < Product.Length; i++)
{
Products Prod = new Products();
Prod._ID = Product[i]._ID;
Prod._Name = Product[i]._Name;
Prod._Price = Product[i]._Price;
Prod._Qte = Product[i]._Qte;
Prod._CAT = Product[i]._CAT;
Prod._Vote = Product[i]._Vote;
Prod._Image = Product[i]._Image;
Prod.ms = new MemoryStream(Prod._Image);
Convert(Prod.ms,Prod._Img);
Produc.Add(Prod);
}
return Produc;
}
So I tried to convert it that way :
public static async void Convert(MemoryStream mem, BitmapImage Img)
{
IRandomAccessStream a1 = await ConvertToRandomAccessStream(mem);
Img = new BitmapImage();
await Img.SetSourceAsync(a1);
}
public static async Task<IRandomAccessStream> ConvertToRandomAccessStream(MemoryStream memoryStream)
{
var randomAccessStream = new InMemoryRandomAccessStream();
var outputStream = randomAccessStream.GetOutputStreamAt(0);
var dw = new DataWriter(outputStream);
var task = Task.Factory.StartNew(() => dw.WriteBytes(memoryStream.ToArray()));
await task;
await dw.StoreAsync();
await outputStream.FlushAsync();
return randomAccessStream;
}
it returns Image as Bytes I didnt Find any idea on how to display it in my Image Control
From your code Log._Image = (byte[])Table.Rows[i]["Image"];, I think your Bytes means byte array here. I think problem is you need to know how your images are converted from image to byte arrays. I assumed that your wcf is for saving data (include byte arrays of images) to table and retrieve them, your converting images to byte arrays work is still done in the UWP app, then I've tested your code, if I convert image to byte array in UWP app in this way:
var file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/1.jpeg"));
var b64 = await ConvertStorageFileToBase64String(file);
private async Task<byte[]> ConvertStorageFileToBase64String(StorageFile File)
{
var stream = await File.OpenReadAsync();
using (var dataReader = new DataReader(stream))
{
var bytes = new byte[stream.Size];
await dataReader.LoadAsync((uint)stream.Size);
dataReader.ReadBytes(bytes);
return bytes;
}
}
And convert back using your method like this:
MemoryStream mem = new MemoryStream(b64);
IRandomAccessStream a1 = await ConvertToRandomAccessStream(mem);
var Img = new BitmapImage();
await Img.SetSourceAsync(a1);
myimg.Source = Img; //myimg is the name of the image control.
The image can be correctly showed in image control. So if your code can't work by your side, please update your code for converting image to byte array, or maybe you can upload your sample so can we have a test.

Encrypt & Decrypt Local Images in Windows Store App

I'm building a Windows Store App including a local folder of Images.
I want to protect all the Images so they can't be accessed from:
C:\Users[username]\AppData\Local\Packages\LocalState\Settings\settings.dat
I know I should encrypt and decrypt the Images using the DataProtectionProvider class, but the documentation only shows how to encrypt/decrypt strings...
How should I convert a Bitmap image into a byte array? or should I encode it with Base64? Is there any tutorial or sample using this process?
It's easiest if the images you want to encrypt are loaded from files and written back out to files. Then you can do:
async void EncryptFile(IStorageFile fileToEncrypt, IStorageFile encryptedFile)
{
IBuffer buffer = await FileIO.ReadBufferAsync(fileToEncrypt);
DataProtectionProvider dataProtectionProvider =
new DataProtectionProvider(ENCRYPTION_DESCRIPTOR);
IBuffer encryptedBuffer =
await dataProtectionProvider.ProtectAsync(buffer);
await FileIO.WriteBufferAsync(encryptedFile, encryptedBuffer);
}
DataProtectionProvider.ProtectStreamAsync is another alternative if you can get stream instances from your inputs and outputs. For example, if you have a byte[] containing your image data then you can create an in-memory input stream from it:
byte[] imageData = ...
using (var inputMemoryStream = new MemoryStream(imageData).AsInputStream())
{
...
}
Edit: Then for example to decrypt the file and display it in an Image control you could do:
var encryptedBuffer = await FileIO.ReadBufferAsync(encryptedFile);
var dataProtectionProvider = new DataProtectionProvider();
var buffer = await dataProtectionProvider.UnprotectAsync(encryptedBuffer);
var bmp = new BitmapImage();
await bmp.SetSourceAsync(buffer.AsStream().AsRandomAccessStream());
imageControl.Source = bmp;
public async void Protect()
{
for (int i = 1; i < 24; i++)
{
string imageFile = ImagePages[i];
var fileToEncrypt = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(imageFile);
var encryptedFile1 = await ApplicationData.Current.LocalFolder.CreateFileAsync("encryptedPage" + i);
var encryptedFile2 = await EncryptFile(fileToEncrypt, encryptedFile1);
IBuffer buffer = await DecryptFile(encryptedFile2);
//(2.) It goes here and throw the 'System.ArgumentException' having the encryptedFile's ContentType=""
var bmp = new BitmapImage();
await bmp.SetSourceAsync(buffer.AsStream().AsRandomAccessStream());
//Fill the List responsible for the Portrait View
MyPortrait mp = new MyPortrait();
mp.onlyImage = bmp;
PImageList.Add(mp);
}
}
public async Task<IStorageFile> EncryptFile(IStorageFile fileToEncrypt, IStorageFile encryptedFile)
{
IBuffer buffer = await FileIO.ReadBufferAsync(fileToEncrypt);
//I have no more exceptions here
DataProtectionProvider dataProtectionProvider = new DataProtectionProvider("LOCAL=user");
IBuffer encryptedBuffer = await dataProtectionProvider.ProtectAsync(buffer);
//(1.) After arriving here when deploying it goes to (2.)
await FileIO.WriteBufferAsync(encryptedFile, encryptedBuffer);
return encryptedFile;
}
public async Task<IBuffer> DecryptFile(IStorageFile encryptedFile)
{
var protectedBuffer = await FileIO.ReadBufferAsync(encryptedFile);
var dataProtectionProvider = new DataProtectionProvider();
var buffer = await dataProtectionProvider.UnprotectAsync(protectedBuffer);
return buffer;
}

Windows 8 How to open a BitmapImage as a stream?

In a Windows 8 app, how do I convert a BitmapImage to a Stream? I have a List of BitmapImages and I'm going to use that List to upload each image to a server and I need to use a Stream to do that. So is there a way to convert each individual BitmapImage into a Stream?
No, there isn't. You need to track the original sources or use a WriteableBitmap instead.
Retrieve the bitmap image:
public async void ContinueFileOpenPicker(FileOpenPickerContinuationEventArgs args)
{
if (args.Files.Count > 0)
{
var imageFile = args.Files[0] as StorageFile;
// Ensure the stream is disposed once the image is loaded
using (IRandomAccessStream fileStream = await imageFile.OpenAsync(Windows.Storage.FileAccessMode.Read))
{
// Set the image source to the selected bitmap
BitmapImage bitmapImage = new BitmapImage();
await bitmapImage.SetSourceAsync(fileStream);
ImageControl.Source = bitmapImage;
await _viewModel.Upload(imageFile);
}
}
}
Create the file stream:
internal async Task Upload(Windows.Storage.StorageFile file)
{
var fileStream = await file.OpenAsync(FileAccessMode.Read);
fileStream.Seek(0);
var reader = new Windows.Storage.Streams.DataReader(fileStream.GetInputStreamAt(0));
await reader.LoadAsync((uint)fileStream.Size);
Globals.MemberId = ApplicationData.Current.LocalSettings.Values[Globals.PROFILE_KEY];
var userName = "Rico";
var sex = 1;
var url = string.Format("{0}{1}?memberid={2}&name={3}&sex={4}", Globals.URL_PREFIX, "api/Images", Globals.MemberId, userName,sex);
byte[] image = new byte[fileStream.Size];
await UploadImage(image, url);
}
Create a memory stream from the image:
public async Task UploadImage(byte[] image, string url)
{
Stream stream = new System.IO.MemoryStream(image);
HttpStreamContent streamContent = new HttpStreamContent(stream.AsInputStream());
Uri resourceAddress = null;
Uri.TryCreate(url.Trim(), UriKind.Absolute, out resourceAddress);
Windows.Web.Http.HttpRequestMessage request = new Windows.Web.Http.HttpRequestMessage(Windows.Web.Http.HttpMethod.Post, resourceAddress);
request.Content = streamContent;
var httpClient = new Windows.Web.Http.HttpClient();
var cts = new CancellationTokenSource();
Windows.Web.Http.HttpResponseMessage response = await httpClient.SendRequestAsync(request).AsTask(cts.Token);
}

Categories