ASP.NET to convert binary data to string - c#

I'm trying to develop API that returns a profile of employees including their pictures, the images are stored in SQL database as image data type
TypeConverter typeConverter = TypeDescriptor.GetConverter(typeof(Bitmap));
Bitmap bmp = (Bitmap)typeConverter.ConvertFrom(Emp.img);
//3
var Fs = new FileStream(HostingEnvironment.MapPath("~/Images") + #"\I" + id.ToString() + ".png", FileMode.Create);
bmp.Save(Fs, ImageFormat.Png);
bmp.Dispose();
//4
Image img = Image.FromStream(Fs);
Fs.Close();
Fs.Dispose();
//5
MemoryStream ms = new MemoryStream();
img.Save(ms, ImageFormat.Png);
//6
response.Content = new ByteArrayContent(ms.ToArray());
ms.Close();
ms.Dispose();
response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
response.StatusCode = HttpStatusCode.OK;
return response;
}
I want to use this API in Android Studio where I have to convert the image data type to string or any other applicable data time with Volley.

I'll use a base64 representation of the image:
byte[] imageAsBytes = File.ReadAllBytes(#"your\path\to\image.png");
string imageAsString = Convert.ToBase64String(imageArray);
Then send it back to the Android Studio client and do the following:
byte[] imageAsStringInAndroidStudio = Base64.decode(encodedImage, Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
Just check if you have to strip the "data:image/jpg;base64" from the data before parsing it into Android Studio.

Related

How to save an Image to Clients System using .Net Core

I have an Image I am retrieving from the database as a byte array. I want to save it outside the Project i.e on the Clients System. I would appreciate if the code aspect can be assisted with. Here is a sample method I have so far:
public Image byteArrayToImage2()
{
var filePath = "C:\\cat.jpg";
byte[] fileBytes = System.IO.File.ReadAllBytes(filePath);
Image returnImage = null;
using (MemoryStream ms = new MemoryStream(fileBytes))
{
returnImage = Image.FromStream(ms);
returnImage.Save("cat2.jpg", ImageFormat.Jpeg);
}
return returnImage;
}
Try the below approach
PS: make sure your fileBytes is of type byte Array.
MemoryStream imageStream = new MemoryStream();
imageStream.Write(fileBytes, 0, fileBytes.Length);
// Include the file name along with extension (Eg: 'C:\TestImage.JPEG')
FileStream fs = File.Create("Give the path where you want to save the image");
imageStream.WriteTo(fs);
fs.Close();
imageStream.Close();

how to convert an image into base64 in xamarin.android?

I have this code, it works very well in android studio but not in xamarin
bitmap.Compress() has different arguments in xamarin and i am confused how to convert image into base64 or binary in xamarin.android?
I am receving an error in the 3rd line:
( bitmap.Compress() has some invalid arguments).
Bitmap bitmap = BitmapFactory.DecodeResource(Resources, Resource.Drawable.ace1);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bitmap.Compress(Bitmap.CompressFormat.Jpeg, 100,bao);
byte[] ba = bao.ToByteArray();
string bal = Base64.EncodeToString(ba, Base64.Default);
If you look at the documentation for Bitmap.Compress in Xamarin, you'll see that the last parameter is a Stream.
The equivalent of ByteArrayOutputStream in .NET is MemoryStream, so your code would be:
Bitmap bitmap = BitmapFactory.DecodeResource(Resources, Resource.Drawable.ace1);
MemoryStream stream = new MemoryStream();
bitmap.Compress(Bitmap.CompressFormat.Jpeg, 100, stream);
byte[] ba = stream.ToArray();
string bal = Base64.EncodeToString(ba, Base64Flags.Default);
(You could use Convert.ToBase64String instead of Base64.EncodeToString if you wanted, too.)
This is how I'm getting a Byte[] for my Bitmap object:
Byte[] imageArray = null;
Bitmap selectedProfilePic = this.GetProfilePicBitmap ();
if (selectedProfilePic != null) {
using (var ms = new System.IO.MemoryStream ()) {
selectedProfilePic.Compress (Bitmap.CompressFormat.Png, 0, ms);
imageArray = ms.ToArray ();
}
}
Hope this helps.

Capturing a byte[] image data from WPFMediaKit

I have a bit of code that I have been working with to capture an image from a VideoCaptureElement from WPFMediaKit. it works great!
bmp.Render(videoElement);
BitmapEncoder encoder = new JpegBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bmp));
string now = DateTime.Now.Year + "" + DateTime.Now.Month + "" + DateTime.Now.Day + "" + DateTime.Now.Hour + "" + DateTime.Now.Minute + "" + DateTime.Now.Second;
string filename = now + "pic.jpg";
FileStream fstream = new FileStream(filename, FileMode.Open);
encoder.Save(fstream);
fstream.Close();
The problem I am facing though is that I need to get a byte[] data now rather than save a file. Currently I am doing this with a open filedialog box and a filestream:
if (File.Exists(FileLocation))
{
//Retreave image from file and binary it to Object image
using (FileStream stream = File.Open(FileLocation, FileMode.Open))
{
BinaryReader br = new BinaryReader(stream);
byte[] data = br.ReadBytes(maxImageSize);
image = new Image(dlg.SafeFileName, data, fileSize);
}
}
What I'd like to do is to take the capture and rather than save a file, I'd like to get it as a byte[] type. Is there a way to convert either RenderTargetBitmap or BitmapEncoder to a byre[] array? Or possibly I'm thinking to convert those to a memory stream so a binary reader can use it?
thanks!
To convert an BitmapSource to a byte array you can do something like this,
Where bmp is your BitmapSource or RenderTargetBitmap.
BitmapEncoder encoder = new JpegBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bmp));
byte[] arr = null;
using (MemoryStream memStream = new MemoryStream())
{
encoder.Save(memStream);
arr = stream.ToArray();
}
In addition to the already mentioned saving to a stream in bmp format, you can also call CopyPixels on a BitmapSource.
That will give you the original pixels, in the original format, with no header.
See this msdn link

send image in pixels using .net webservice

i wrote a webservice for send image in pixels form. it is working fine but when we give large amount of data in parameter it do not take full data. it take limited data or small image.
is this parameter limit? or How i give large data in parameter?
Here is my code
[WebMethod]
public XmlDocument testuploadimage(string image)
{
XmlDocument login = new XmlDocument();
XmlDeclaration dec = login.CreateXmlDeclaration("1.0", null, null);
login.AppendChild(dec);
XmlElement root = login.CreateElement("CreateUser");
login.AppendChild(root);
try
{
string actFolder = Server.MapPath("~/Images/");
string s = image.Replace(" ", string.Empty);
string imgname = DateTime.UtcNow.ToString().Replace(" ", "").Replace("AM", "").Replace("PM", "").Replace("/", "").Replace("-", "").Replace(":", "") + ".png";
// string imgname = DateTime.UtcNow.ToString("yyyyMMddHHmm") + ".png";
byte[] imageBytes = Convert.FromBase64String(image.Replace(" ","+"));
MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
// MemoryStream ms = new MemoryStream(imageBytes);
// Convert byte[] to Image
// ms.Write(imageBytes, 0, imageBytes.Length);
Image image2 = Image.FromStream(ms);
image2.Save(actFolder + imgname);
XmlElement root1 = login.CreateElement("uploaded");
root1.InnerText = "true";
root.AppendChild(root1);
XmlElement root2 = login.CreateElement("path");
root2.InnerText = "http://Myserver/HeritageWebServices/Images/" + imgname;
root.AppendChild(root2);
return login;
}
catch (Exception ex)
{
ErrLogMgr.LogErrorMessage(string.Format("{0}{1}", "testuploadimage() for the image :",
image), "testUploadimage Inputs",
ERRORSOURCE.CSASERVICE);
XmlDocument cd = new XmlDocument();
cd.LoadXml("<Message>" + ex + "</Message>");
return cd;
Two things
Try to change the maxRequestLength on the web.config file.
i see that you are using base64 to send the image, you could try to compress the bytearray before convert it to base64, to reduce the image or try to convert to a more compressed image type (ej: bmp to png).
regards

How to convert varBinary into image or video when retrieved from database in C#

I am using visual studio 2010, (desktop application) and using LINQ to SQL to save image/video or audio files to database in dataType VarBinary (MAX). This I can do... Problem is, I can't get them and display them in xaml because I can't get the converting part correct. Here is what I have so far (though its not working);
private void bt_Click (object sender, RoutedEventArgs e)
{
databaseDataContext context = new databaseDataContext();
var imageValue = from s in context.Images
where s.imageID == 2
select s.imageFile;
value = imageValue.Single().ToString();
//convert to string and taking down to next method to get converted in image
}
public string value { get; set; }
public object ImageSource //taking from http://stackoverflow.com/
{
get
{
BitmapImage image = new BitmapImage();
try
{
image.BeginInit();
image.CacheOption = BitmapCacheOption.OnLoad;
image.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
image.UriSource = new Uri(value, UriKind.Absolute);
image.EndInit();
Grid.Children.Add(image);
}
catch { return DependencyProperty.UnsetValue; } return image;
}
}
I not even sure if I am on the correct track? And I am assuming that video or audio is quite similar methods?
Since your image is stored in binary format in the database, you want to "stream" this into an image object by leveraging the MemoryStream object.
Looking at your code, your solution will look something like this:
BitmapImage bmpImage = new BitmapImage();
MemoryStream msImageStream = new MemoryStream();
msImageStream.Write(value, 0, value.Length);
bmpCardImage.BeginInit();
bmpCardImage.StreamSource = new MemoryStream(msImageStream.ToArray());
bmpCardImage.EndInit();
image.Source = bmpCardImage;
It's very easy, if you have a binary data and want to create an Image object, use this code:
public Image BinaryToImage(byte[] binaryData)
{
MemoryStream ms = new MemoryStream(binaryData);
Image img = Image.FromStream(ms);
return img;
}
If you already have the bytes, to verify that what you saved is correct you can save the bytes to a file and open it....
string tempFile = Path.GetTempFileName();
MemoryStream ms = new MemoryStream(bytes); //bytes that was read from the db
//Here I assume that you're reading a png image, you can put any extension you like is a file name
FileStream stream = new FileStream(tempFile + ".png", FileMode.Create);
ms.WriteTo(stream);
ms.Close();
stream.Close();
//And here we open the file with the default program
Process.Start(tempFile + ".png");
And later you can use the answer of Dillie-O and stream....
Dillie-O's code makes for a very nice extension method:
// from http://stackoverflow.com/questions/5623264/how-to-convert-varbinary-into-image-or-video-when-retrieved-from-database-in-c:
public static BitmapImage ToImage(this Binary b)
{
if (b == null)
return null;
var binary = b.ToArray();
var image = new BitmapImage();
var ms = new MemoryStream();
ms.Write(binary, 0, binary.Length);
image.BeginInit();
image.StreamSource = new MemoryStream(ms.ToArray());
image.EndInit();
return image;
}

Categories