Displaying a byte[] in an image control - c#

So I collect a varbinary(MAX) value from a database where an image is stored.
It gets converted to byte[], then the aim is to display this in an image control.
This is where I read from the database
public TemplateData(SqlDataReader dr)
{
initialiseData();
if (dr.HasRows)
{
Logo = (byte[])dr["Logo"];
//Logo = dr["Logo"].ToString();
TemplateId = dr["TemplateId"].ToString();
Comment = dr["Comment"].ToString();
SchemeCode = dr["SchemeCode"].ToString();
Version = dr["Version"].ToString();
}
}
This is where the values are displayed into the corresponding controls
protected void ddSchemeCode_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddSchemeCode.SelectedIndex > 0)
{
// Existing Data to load from database
TemplateData temp = DataClass.ReturnData(ddSchemeCode.SelectedItem.Text);
if (temp != null)
{
txtVersion.Text = temp.Version;
txtComment.Text = temp.Comment;
txtSchemeCode.Text = temp.SchemeCode;
txtTemplateId.Text = temp.TemplateId;
img.Src = temp.Logo;
}
So at the moment I am passing a byte[] into the source of an image control, where it would instead like a string. I've tried converting it to a string with Convert.ToBase64String(Logo) and ToString(Logo) but these do not work.
Any help is greatly appreciated. Cheers guys and gals.

Try converting the byte array to image and assign it to picturebox as below,
try
{
using (MemoryStream mStream = new MemoryStream())
{
// where pData is your byte array
mStream.Write(pData, 0, Convert.ToInt32(pData.Length));
Image originalImage = Image.FromStream(mStream);
picBox.Image = originalImage;
}
}
catch (Exception ex)
{
}
Hope it helps.

As you may have noticed, you cannot "print" an image in a webpage. You need to get a little bit creative now.
What you want to look into is Response.BinaryWrite. More information about that, here: https://msdn.microsoft.com/en-us/library/system.web.httpresponse.binarywrite%28v=vs.110%29.aspx
You will probably also need a generic ashx handler. Here is an example of how to show a picture using a handler: http://www.dotnetperls.com/ashx
My suggestion would be to store the logo as a byte[] into the http session. Put the source of the image to theHttpHandlerYourGonnaCreate.ashx. You can then binary write the byte[] you've stored into the session there.
Hope this helps!

As Michael shows here, you can convert the byte array to a Bitmap object with something like this:
Bitmap bitmap = null;
using (MemoryStream imageStream = new MemoryStream(imageData))
{
bitmap = new Bitmap(imageStream);
}
It isn't entirely clear what you're using for a control to show the image, but any control that can display an image should be able to take a Bitmap or Image object.

Related

Display ImageSharp Image in Avalonia UI

As the title says. It seems that Avalonia Bitmap requires file path, so the only solution that comes to my mind is saving image, and then displaying it. But it's not exactly what I want to do, I would want to directly display the image from memory.
public void ReadAndDisplayImage()
{
ReadWrite rw = new ReadWrite();
var image = rw.ReadImage(ImagePath); //ImageSharp Image
SelectedImage = new Avalonia.Media.Imaging.Bitmap(ImagePath); //constructor accepts only string, unable to display ImageSharp Image directly
}
In this case here displaying from path is fully acceptable, but later I will need to display it without saving.
You can save the Image's data into a memory stream and pass it in to Avalonia's Bitmap.
public void ReadAndDisplayImage()
{
ReadWrite rw = new ReadWrite();
var image = rw.ReadImage(ImagePath);
using (MemoryStream ms = new MemoryStream())
{
image.Save(ms,PngFormat.Instance);
SelectedImage = new Avalonia.Media.Imaging.Bitmap(ms);
}
}

How can i make byte array from NEF or another RAW Format and edit it?

im trying to make simple photo editor (for adjusting brightness, contrast, saturation etc...) in WPF and im using the Magick.NET which contains ToByteArray method but the problem is i can't make ByteArray with this method because i'm getting exception because it doesn't wanna make ByteArray from NEF format for some reason...
My first idea, was to take the NEF format convert it to temporary TIFF File which can be converted with this specific method to ByteArray and that file can be converted to bytearray, but i think is very inconvenient and not much smart.
Second thing is when i have the WritableBitmap. How can i make the image from it for Magick.NET to edit it? Should i make another MagickImage Instance which is created with already created ByteArray and edit that image?
public void ImageSelectBtn_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog();
if (dialog.ShowDialog() == true)
{
using (var imageRaw = new MagickImage(dialog.FileName))
{
imageRaw.Write("D:/Coding/C#/New/SoftlightWPF/SoftlightWPF/Resources/temp.tiff");
MagickImage image = new MagickImage();
image = new MagickImage("D:/Coding/C#/New/SoftlightWPF/SoftlightWPF/Resources/temp.tiff");
byte[] ImageBytes = image.ToByteArray();
Render(ImageBytes);
}
}
}
private void Render(byte[] BytesData)
{
using (var ms = new MemoryStream(BytesData))
{
BitmapImage ImageBitmapSource = new BitmapImage(); //Image
ImageBitmapSource.BeginInit();
ImageBitmapSource.CacheOption = BitmapCacheOption.OnLoad;
ImageBitmapSource.StreamSource = ms;
ImageBitmapSource.EndInit();
WriteableBitmap ImageWritableBitmap = new WriteableBitmap(ImageBitmapSource);
this.ImageField.Source = ImageWritableBitmap;
}
}
There is already a library that can help you with this: https://www.nuget.org/packages/Magick.NET.SystemWindowsMedia/. Add it to your project and then do image.ToBitmapSource() instead.

c# Load Image from ftp server directly into picture box without downloading

I have looked every where for my answer but couldn't find the right solution.Tried many solutions provided but still can't get it through.I uploaded an image in ftp server and i want it to get displayed into picture box in windows form without downloading it into local machine. Is it possible?
Please include complete code for the solution......
Here is a complete code: If any body needs.Make sure the image isn't large!!
public byte [] GetImgByte (string ftpFilePath)
{
WebClient ftpClient = new WebClient();
ftpClient.Credentials = new NetworkCredential(ftpUsername,ftpPassword);
byte[] imageByte = ftpClient.DownloadData(ftpFilePath);
return imageByte;
}
public static Bitmap ByteToImage(byte[] blob)
{
MemoryStream mStream = new MemoryStream();
byte[] pData = blob;
mStream.Write(pData, 0, Convert.ToInt32(pData.Length));
Bitmap bm = new Bitmap(mStream, false);
mStream.Dispose();
return bm;
}
You can use DownloadData to get a byte array and load that into the picturebox - see Download file directly to memory and How to put image in a picture box from a byte[] in C#

Cannot convert System.Drawing.Image to EmguCV

Currrently, I am trying to get my face image from the database but I cannot get it. Its saying my I cannot convert System.Drawing.Image to EmguCV Gray Byte. Can I know whats my mistake on it. This is my first time I am using EmguCV.
//Eigen face recognizer
EigenObjectRecognizer recognizer = new
GetFaceFromDB(), //database
labels.ToArray(), //facename list
3000,
ref termCrit);
name = recognizer.Recognize(result);
This is my DB code:
private Image GetFaceFromDB()
{
Image FetchImg;
if (rowNumber >= 0)
{
byte[] FetchImgBytes = ((byte[])TSTable.Rows[rowNumber]["FaceImage"]);
System.IO.MemoryStream stream = new System.IO.MemoryStream(FetchImgBytes);
FetchImg = Image.FromStream(stream);
return FetchImg;
}
else
{
MessageBox.Show("No Image yet. Add image into database");
return null;
}
}
Thank you.
Well the problem is the conversion.
If you are using an image like this
Image<Gray,Byte> image = new Image<Gray,Byte>
initialized like this then you need to call image.Bitmap to get a System.Drawing.Image
If you are trying to do the reverse you should call something like this
Image<Gray, Byte> image = new Image<Gray, Byte>(BitmapImage);
Then your code should work correctly.
Hope this helps!

how to add empty image to table

I want if user do not set image for picturebox save empy image in table .
my code is :
byte[] arrImage;
if (picperson.Image != null)
{
//convert image to byte
MemoryStream ms = new MemoryStream();
picperson.Image.Save(ms, picperson.Image.RawFormat);
arrImage = ms.GetBuffer();
ms.Close();
}
else arrImage = null;
objcommand.Parameters.AddWithValue("#picture", arrImage);
when he adds null image, exception occurs on line picperson.Image.Save(ms, picperson.Image.RawFormat);
How to add empty imag to table ?
You can't pass a null value for your image parameter, so a work around would be to send in a zero byte array:
if (picperson.Image != null) {
//convert image to byte
} else {
arrImage = new byte[0];
}
Unfortunately, that will not set the field to null.
To set the field to null would probably be handled best with a separate query, for example:
using (SqlCommand q = new SqlCommand("INSERT INTO M (MyImage) VALUES (null)", cn)
...
which does not use parameters.
As far as reading some of the comments are concerned, it sounds like the image format needs to be specified. Try using the actual format that you want the image saved as:
picperson.Image.Save(ms, ImageFormat.Bmp);
// or
picperson.Image.Save(ms, ImageFormat.Jpeg); // or Png, etc.

Categories