showing image in gridview from byte array - c#

I have a following problem:
I am using c# and .aspx pages. On .aspx page i have a GridView. I set a GridView datasource to be:
GridView1.DataSource = PictureInfo.PictureInfoList;
My "PictureInfo" class looks like this:
public class PictureInfo
{
public static List<PictureInfo> PictureInfoList = new List<PictureInfo>();
public string PictureDescription { get; set; }
public byte[] Picture { get; set; }
}
Is it possible and how to show a picture which is in "byte[] Picture" in a GridView? Or which way it is possible? I'm saving data in this way before i send it to a database. And i would like to show it in a GridView before i send it to a database. As you can see I'm a beginner but i would be very happy if i could make this work. My head hearts already from reading some solutions online, none helped until now.
thank you very much

I suggest you a solution for: Converting byte[] to Bitmap (may it will be useful for you):
public BitmapSource ByteArrayToBitmap(byte[] byteArray) {
BitmapSource res;
try {
using (var stream = new MemoryStream(byteArray)) {
using (var bmp = new Bitmap(stream)) {
res = ToBitmap(bmp);
}
}
} catch {
res = null;
}
return res;
}
public BitmapSource ToBitmap(Bitmap bitmap) {
using (var stream = new MemoryStream()) {
bitmap.Save(stream, ImageFormat.Bmp);
stream.Position = 0;
var result = new BitmapImage();
result.BeginInit();
result.CacheOption = BitmapCacheOption.OnLoad;
result.StreamSource = stream;
result.EndInit();
result.Freeze();
return result;
}
}
Next, you should adapt, and include the Bitmap in your GridView.

on your handler.ashx
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "image/jpeg";
string ImageID=request["ID"];
//byte[] ImageByte=pictureInfo.Picture;//local imageByte
byte[] ImageByte=getImage(ImageId);//image byte from any other sour,e.g database
Stream strm = new MemoryStream(ImageByte));
long length = strm.Length;
byte[] buffer = new byte[length];
int byteSeq = strm.Read(buffer, 0, 2048);
while (byteSeq > 0)
{
context.Response.OutputStream.Write(buffer, 0, byteSeq);
byteSeq = strm.Read(buffer, 0, 2048);
}
}
now set image url for your asp:image inside your gridview as follows
Image1.ImageUrl = "somthing.ashx?ID="+userImageID;
i hope you have unique id for your image to be visible. I hope you have all set now. Comments and query are well comed.
retrieve image byte from database
public byte[] GetImage(string ImageId)
{ byte[] img = null;
DataTable dt = new DataTable();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "SlikaHendler";
cmd.Parameters.AddWithValue("#Id", ImageId);
cmd.Connection = yourConnection();
SqlDataReader dr = null;
dr = cmd.ExecuteReader();
if (dr.Read())
{
img = (byte[])dr[0];
}
dr.Close();
return img;//returns array of byte
}

I know pictures are recorded as binaries to databases. In this aspect, your problem turns to a "converting binary to byte".
If you can reach your picture info as binary data, you can convert it as taking 3 digits for 1 byte, and convert & show as bytes.
http://en.wikipedia.org/wiki/ASCII

Related

I want to save image in jpg format from SQL Server database but when I download it , it has only 1KB size and cannot be opened

private void Msg1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
string SaveFileTo = "D:\\DA.jpg";
// string SaveFileTo = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
// string filename = "jmk.jpg";
// SaveFileTo = Path.Combine(SaveFileTo, filename);
CN.Open();
SqlCommand cmd = new SqlCommand("select photo from edistindata where enrollno='" + CboEnroll.Text + "' ", CN);
DR = cmd.ExecuteReader();
byte[] data = null;
while (DR.Read())
{
data = (byte[])DR["Photo"];
}
using (var fs = new FileStream(SaveFileTo, FileMode.Create, FileAccess.Write))
{
fs.Write(data,0,data.Length);
}
MessageBox.Show("Success");
}
I have run the code in the question, even it has some of not good coding practices, if the data in the photo column is not corrupted it should produce the image file.
so I have put down your code with proper enhancements that will flag you early before saving corrupted data.
private void Msg1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
ImageCodecInfo theJpgCodecInfo = ImageCodecInfo.GetImageEncoders()
.FirstOrDefault(encoder => encoder.MimeType == "image/jpeg");
var myEncoder = Encoder.Quality;
var myEncoderPrams = new EncoderParameters(1);
myEncoderPrams.Param[0] = new EncoderParameter(myEncoder, 100L);
string SaveFileTo = "D:\\DA";
// string SaveFileTo = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
// string filename = "jmk.jpg";
// SaveFileTo = Path.Combine(SaveFileTo, filename);
CN.Open();
SqlCommand cmd = new SqlCommand("select photo from edistindata where
enrollno=#Enrol;", CN);
cmd.Parameters.AddWithValue("#Enrol", CboEnroll.SelectedItem.ToString());
DR = cmd.ExecuteReader();
byte[] data = null;
int idx = 0;
while (DR.Read())
{
data = (byte[])DR["Photo"];
Image tempImage;
try
{
tempImage = ByteArrayToImage(data);
}
catch (Exception exc)
{
MessageBox.Show(exc.GetType().ToString()
+Environment.NewLine+exc.Message);
continue;
}
var tempBitmap = new Bitmap(tempImage);
var tempFname = "D:\\DA"+(idx++).ToString()+".jpg";
tempBitmap.Save(tempFname, theJpgCodecInfo, myEncoderPrams);
}
}
public static Image ByteArrayToImage(byte[] byteArrayIn)
{
using (MemoryStream ms = new MemoryStream(byteArrayIn))
{
Image returnImage = Image.FromStream(ms);
return returnImage;
}
}
The enhancements that I suggested as follow:
As #derpirscher mentioned in his comment use parameters not string concatenation when building SQL commands and the easiest most lazy way to do it is Parameters.AddWithValue().
Use CboBox.SelectedItem.ToString in place of the .Text as been in your code.
instead of dumping the byte[] directly through a FileStream.Write() I transferred the byte array into Image() then into Bitmap().
this way if the byte[] (and hence the data in the db column photo) is not one of the binary formats the the class Image() can handle it will throw exception and I used that to show the related error.
Also, this way we over came some issues that may rise if we used Bitmap() directly if the data byte[] contains PNG format.
No matter what image format is stored in the photo column it will be legitimately re-encoded as Jpeg then saved.

Why is my image (from database) not displaying properly in my pictureBox?

I save my image like this:
//This is in my ImageConverter class:
public static byte[] ConvertImageToByteArray(Image userImage) //Get bytes of the image
{
using (MemoryStream ms = new MemoryStream())
using (Bitmap tempImage = new Bitmap(userImage))
{
tempImage.Save(ms, userImage.RawFormat);
return ms.ToArray();
}
}
//this is in my save button:
sqlCmd.Parameters.Add("#user_image", SqlDbType.VarBinary, 8000).Value =
ImageConverter.ConvertImageToByteArray(pictureBox1.Image);
I retrieve my image by clicking on the datagridview like this:
private void dgvEmpDetails_CellClick(object sender, DataGridViewCellEventArgs e)
{
try
{
if (e.RowIndex != -1)
{
//Display user image
using (SqlConnection con = new SqlConnection(connectionStringConfig))
using (SqlCommand sqlCmd = new SqlCommand(
"SELECT user_image FROM dbo.Employee_Image
WHERE employee_id=#employee_id", con))
{
con.Open();
sqlCmd.Parameters.Add("#employee_id",
SqlDbType.NVarChar).Value = EmployeeId;
using (SqlDataReader reader = sqlCmd.ExecuteReader())
{
if (reader.HasRows)
{
reader.Read();
pictureBox1.Image = ImageConverter.
ConvertByteArrayToImage((byte[])(reader.GetValue(0)));
}
else
{
pictureBox1.Image = null;
}
}
}
}
}
catch (Exception ex)
{
MessageBox.Show($"Something is wrong with the selected record!
\nError: { ex.Message }");
}
}
//This is in my ImageConverter class:
public static Image ConvertByteArrayToImage(byte[] buffer) //Get image from database
{
using (MemoryStream ms = new MemoryStream(buffer))
{
return Image.FromStream(ms);
}
}
NOTE: I don't display my image's binary data in my datagridview.
Saving and updating the image (with the users records) works fine.
After saving an image to the database, it does not display properly. But when I load it using OpenFileDialog the image displays just fine.
Loading the image using OpenFileDialog:
When I click a datagridview row to view a user record this is what the pictureBox looks like:
Why is this split in some sort? I have not seen any similar problem/solution about this. Most of them is about "Loading image from the database to pictureBox". But I have already done that.
Try using the MemoryStream.Write method.
Change this:
//This is in my ImageConverter class:
public static Image ConvertByteArrayToImage(byte[] buffer) //Get image from database
{
using (MemoryStream ms = new MemoryStream(buffer))
{
return Image.FromStream(ms);
}
}
to this:
//This is in my ImageConverter class:
public static Image ConvertByteArrayToImage(byte[] buffer) //Get image from database
{
using (MemoryStream ms = new MemoryStream)
{
ms.Write(buffer.ToArray(), 0, buffer.Length);
return Image.FromStream(ms);
}
}
This is my approach for getting images from database
// This method use to update the form.
private void loadFormWithID(int ID)
{
dbServer conn = new dbServer(sysController.getConn);
DataTable tbl = conn.getQueryList("SELECT * FROM Products WHERE ID = " + ID);
DataRow row = tbl.Rows[0];
// This is how i update the Picture Box
pictureBoxItem.Image = row["Image"] == DBNull.Value ? pictureBoxItem.InitialImage : ImageController.bytesToImage((byte[])row["Image"]);
}
This is my dbserver class which communicates with database.
public class dbServer
{
public string _connectionLink;
public dbServer(string connectionString)
{
_connectionLink = connectionString;
}
public DataTable getQueryList(string sqlQuery)
{
DataTable tbl = new DataTable();
using (SqlConnection conn = new SqlConnection(_connectionLink))
{
using (SqlCommand cmd = new SqlCommand(sqlQuery, conn))
{
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
tbl.Load(reader);
}
}
return tbl;
}
}
I hope this solves the Issue.
This is what i used for my database image retriever.
class ImageController
{
public static byte[] ImageToBytes(PictureBox pb)
{
MemoryStream ms = new MemoryStream();
pb.Image.Save(ms, pb.Image.RawFormat);
return ms.GetBuffer();
}
public static byte[] ImageToBytes(Image pb)
{
MemoryStream ms = new MemoryStream();
pb.Save(ms, pb.RawFormat);
Console.WriteLine(ms.Length);
return ms.GetBuffer();
}
public static Image bytesToImage(byte[] imageRaw)
{
MemoryStream ms = new MemoryStream(imageRaw);
return Image.FromStream(ms);
}
}
Here's a complete solution, which seems to work with SQL Server Express/SQL Server:
Note: When the table in the database is created, column User_Image should be created as varbinary(MAX)
Read image from file and return as byte[]:
Note: I've included 3 different ways to read an image file and return a byte[]. GetImageFromFile seems to produce a byte array that has the same number of bytes as the original (tested with .jpg), whereas, GetImageFromFilev2 and GetImageFromFilev3, have fewer bytes. See How to convert image to byte array for more information.
public static byte[] GetImageFromFile(string filename)
{
byte[] rawData = null;
try
{
if (!String.IsNullOrEmpty(filename) && System.IO.File.Exists(filename))
{
using (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read))
{
//get length of file - in bytes
int fileLength = (int)fs.Length;
//create new byte array
rawData = new byte[fileLength];
//read data into byte array (rawData)
fs.Read(rawData, 0, fileLength);
fs.Flush();
Debug.WriteLine("rawData.Length: " + rawData.Length);
}
}
}
catch (Exception ex)
{
//ToDo: log message
throw ex;
}
return rawData;
}
public static byte[] GetImageFromFilev2(string filename)
{
byte[] rawData = null;
try
{
if (!String.IsNullOrEmpty(filename) && System.IO.File.Exists(filename))
{
using (Image image = Image.FromFile(filename))
{
using (MemoryStream ms = new MemoryStream())
{
image.Save(ms, image.RawFormat);
rawData = ms.ToArray();
}
}
}
}
catch (Exception ex)
{
//ToDo: log message
throw ex;
}
return rawData;
}
public static byte[] GetImageFromFilev3(string filename)
{
byte[] rawData = null;
try
{
if (!String.IsNullOrEmpty(filename) && System.IO.File.Exists(filename))
{
using (Image image = Image.FromFile(filename))
{
ImageConverter ic = new ImageConverter();
rawData = (byte[])ic.ConvertTo(image, typeof(byte[]));
Debug.WriteLine("rawData.Length: " + rawData.Length);
}
}
}
catch (Exception ex)
{
//ToDo: log message
throw ex;
}
return rawData;
}
Read image data from database:
public static System.Drawing.Bitmap GetImageFromTblEmployeeImageBitmap(string employee_id)
{
System.Drawing.Bitmap image = null;
byte[] imageData = GetImageFromTblEmployeeImageByte(employee_id);
//convert to Bitmap
if (imageData != null)
{
using (System.IO.MemoryStream ms = new System.IO.MemoryStream(imageData))
{
image = new System.Drawing.Bitmap(ms);
ms.Flush();
}
}
return image;
}
public static byte[] GetImageFromTblEmployeeImageByte(string employee_id)
{
byte[] imageData = null;
try
{
using (SqlConnection cn = new SqlConnection(ConnectStr))
{
string sqlText = "Select user_image from Employee_Image where employee_id = #employee_id";
//open connection to db
cn.Open();
using (SqlCommand cmd = new SqlCommand(sqlText, cn))
{
cmd.Parameters.Add("#employee_id", SqlDbType.NVarChar).Value = employee_id;
//execute
SqlDataReader dr1 = cmd.ExecuteReader();
bool result = dr1.Read();
if (result)
{
imageData = (byte[])dr1["User_Image"];
}
Debug.WriteLine("result: " + result);
}
}
}
catch (SqlException ex)
{
//ToDo: log message
throw ex;
}
catch (Exception ex)
{
//ToDo: log message
throw ex;
}
return imageData;
}
Save image data to database
public static string SaveImageToTblEmployeeImage(string employee_id, string filename)
{
return SaveImageToTblEmployeeImage(employee_id, GetImageFromFile(filename));
}
public static string SaveImageToTblEmployeeImage(string employee_id, byte[] user_image)
{
string status = string.Empty;
using (SqlConnection cn = new SqlConnection(ConnectStr))
{
string sqlText = "INSERT INTO Employee_Image(Employee_Id, User_Image) VALUES (#employee_id, #user_image)";
//open connection to db
cn.Open();
using (SqlCommand cmd = new SqlCommand(sqlText, cn))
{
//add parameters
cmd.Parameters.Add("#employee_id", System.Data.SqlDbType.NVarChar).Value = employee_id;
//for varbinary(max) specify size = -1, otherwise there is an 8000 byte limit
//see https://learn.microsoft.com/en-us/dotnet/api/system.data.sqldbtype?view=netframework-4.8
cmd.Parameters.Add("#user_image", System.Data.SqlDbType.VarBinary, -1).Value = user_image;
//execute
int numRowsAffected = cmd.ExecuteNonQuery();
status = "Data inserted into table 'Employee_Image'";
Debug.WriteLine("numRowsAffected: " + numRowsAffected);
}
}
return status;
}
Upload image to database
using (OpenFileDialog ofd = new OpenFileDialog())
{
ofd.Filter = "Image Files (*.bmp;*.gif;*.jpg;*.jpeg;*.png)|*.bmp;*.gif;*.jpg;*.jpeg;*.png|All Files (*.*)|*.*";
if (ofd.ShowDialog() == DialogResult.OK)
{
SaveImageToTblEmployeeImage("12345", ofd.FileName);
}
}
To display image in PictureBox (ex: pictureBox1)
Bitmap image = GetImageFromTblEmployeeImageBitmap("12345");
if (image != null)
{
pictureBox1.Image = image;
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage; //fit to size
pictureBox1.Refresh();
}
Resources:
Getting binary data using SqlDataReader
How to save image in database using C#
SqlDbType Enum

how to get Image from DataSet

i have DataSet that contain Image.
i need to save this Image to File.
i try this:
SQL = ItemCode,PIC from ROW;
dsView = new DataSet();
adp = new SqlCeDataAdapter(SQL, Conn);
adp.Fill(dsView, "ROW");
adp.Dispose();
foreach (DataRow R in dsROW.Tables[0].Rows)
{
ItemCode = R["ItemCode"].ToString().Trim() ;
TEMP = R["PIC"].ToString().Trim();
Image image = R["PIC"] as Image;
if(image != null)
{
MemoryStream ms = new MemoryStream();
image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] imagedata = ms.ToArray();
}
but image Always is null
and in TEMP i see System.Byte[]
need some help, thanks
Your R["PIC"] is an array or Bytes.
First, you try to apply ToString() to it, and you simply get System.Byte[].
Then, you try to cast it to Image. How is Byte[] supposed to cast to Image?
You need to create an Image from your Byte array:
dsView = new DataSet();
adp = new SqlCeDataAdapter(SQL, Conn);
adp.Fill(dsView, "ROW");
adp.Dispose();
foreach (DataRow R in dsROW.Tables[0].Rows)
{
ItemCode = R["ItemCode"].ToString().Trim();
using (var ms = new MemoryStream(R["PIC"]))
{
Image image = Image.FromStream(ms);
image.Save($"C:\\Output\\YourCustomPath\\{ItemCode}.jpeg", ImageFormat.Jpeg);
}
}
You need to read the data in sequential access mode. Here is an example I use to read binary data. See the use of
SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.SequentialAccess);
snippet:
string sql = "Select file_data from utils where util_id="+uID.ToString()+";";
SqlCommand cmd = new SqlCommand(sql, database._sqlConnection);
SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.SequentialAccess); // CommandBehavior.SequentialAccess: read columns in order and every column only once!
int columnNr = 0;
byte[] filedata = null;
try
{
while (rdr.Read())
{
//load the binary data
if (rdr.IsDBNull(columnNr)) //is there any binary data? //LAST COLUMN!!!!!
filedata = null;
else
{
//read binary data
int bufferSize = 100; // Size of the BLOB buffer.
byte[] outbyte = new byte[bufferSize]; // The BLOB byte[] buffer to be filled by GetBytes.
long retval; // The bytes returned from GetBytes.
long startIndex = 0; // The starting position in the BLOB output.
MemoryStream ms = new MemoryStream();
BinaryWriter bw = new BinaryWriter(ms);
// Reset the starting byte for the new BLOB.
startIndex = 0;
// Read the bytes into outbyte[] and retain the number of bytes returned.
retval = rdr.GetBytes(columnNr, startIndex, outbyte, 0, bufferSize);
// Continue reading and writing while there are bytes beyond the size of the buffer.
while (retval >0) //== bufferSize)
{
bw.Write(outbyte);
bw.Flush();
// Reposition the start index to the end of the last buffer and fill the buffer.
startIndex += bufferSize;
retval = rdr.GetBytes(columnNr, startIndex, outbyte, 0, bufferSize);
}
bw.Close();
filedata = ms.ToArray();
ms.Close();
}
}
}
catch (SqlException ex)

ASP MVC can't display image in view

So I've got this image in the shape of a byte[] that I want to display in my view.
This is my model of the image:
public class ImageModel
{
public Byte[] imageFirst { get; set; }
}
This is my controller picking out the image from a db:
public ActionResult Image()
{
string cs = "Data Source=" + Environment.CurrentDirectory + "\\ImageDB.db";
using (SQLiteConnection con = new SQLiteConnection(cs))
{
var listOfImages = new List<ImageModel>();
string stm = "SELECT * FROM Image";
con.Open();
using (SQLiteCommand cmd = new SQLiteCommand(stm, con))
{
using (SQLiteDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
listOfImages.Add(new ImageModel
{
imageFirst = Serialize(rdr["image_first"]),
});
}
rdr.Close();
Images = listOfImages;
}
}
con.Close();
}
return View(Images);
}
public static byte[] Serialize(object obj)
{
var binaryFormatter = new BinaryFormatter();
var ms = new MemoryStream();
binaryFormatter.Serialize(ms, obj);
return ms.ToArray();
}
And this is when I try to show the image in the view:
<img src="data:image/jpg;base64,#(Convert.ToBase64String(#item.imageFirst))" width="300px"/>
But all I get is this icon:
I can't for the love of me figure out why it can't be shown. The images are stored as what I can only assume is a blob in the database, but right now I wish they were just image files on the disc, as that seems to make it a lot easier to attach them to the view.
Assuming the imageFirst property is a valid image byte array, you may need to include html raw mode on the output:
<img src="data:image/jpg;base64,#Html.Raw(Convert.ToBase64String(item.imageFirst))" width="300px"/>
Also, use item instead of #item since you are already inside of #(), or in the example #Html.Raw.
Which browser you are using. IE has a size limit on the data URI, I think it is 32 KB. What is the size of your image string after converting to base64.

WPF Returing Bitmap Image to browser - Self hosted Owin Application

I am working on a Self Hosted WPF Application (using Owin) that returns bitmap images to the browser.
My controller code looks like this:
public ImageSource GetmbTiles(string FILE, string Z, string X, string Y)
{
string mbtiles = string.Format(("C:\\{0}.mbtiles"), FILE);
string connString = string.Format("Data Source={0}", mbtiles);
using (SQLiteConnection conn = new SQLiteConnection(connString))
{
System.Text.StringBuilder Query = new System.Text.StringBuilder();
Query.Append("SELECT tile_data ");
Query.Append("FROM tiles ");
Query.Append(string.Format("where zoom_level={0} and tile_column={1} and tile_row={2} ", Z, X, Y));
using (SQLiteCommand cmd = new SQLiteCommand(Query.ToString(), conn))
{
conn.Open();
using (SQLiteDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
buffer = GetBytes(dr);
}
}
}
}
//return new System.IO.MemoryStream(buffer);
return byteArrayToImage(buffer);
}
private static BitmapImage byteArrayToImage(byte[] imageData)
{
if (imageData == null || imageData.Length == 0) return null;
var image = new BitmapImage();
using (var mem = new MemoryStream(imageData))
{
mem.Position = 0;
image.BeginInit();
image.CreateOptions = BitmapCreateOptions.PreservePixelFormat;
image.CacheOption = BitmapCacheOption.OnLoad;
image.UriSource = null;
image.StreamSource = mem;
image.EndInit();
}
image.Freeze();
return image;
}
private static byte[] GetBytes(SQLiteDataReader reader)
{
const int CHUNK_SIZE = 2 * 1024;
byte[] buffer = new byte[CHUNK_SIZE];
long bytesRead = 0;
long fieldOffset = 0;
using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
{
bytesRead = reader.GetBytes(0, fieldOffset, buffer, 0, buffer.Length);
while (bytesRead == buffer.Length)
{
stream.Write(buffer, 0, Convert.ToInt32(bytesRead));
fieldOffset += bytesRead;
bytesRead = reader.GetBytes(0, fieldOffset, buffer, 0, buffer.Length);
}
stream.Write(buffer, 0, Convert.ToInt32(bytesRead));
return stream.ToArray();
}
}
When I call this controller from my browser I only get a json file and not the image.
The exception Message is
<ExceptionMessage>Type 'System.IO.MemoryStream' with data contract name 'MemoryStream:http://schemas.datacontract.org/2004/07/System.IO' is not expected. Consider using a DataContractResolver if you are using DataContractSerializer or add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to the serializer.</ExceptionMessage>
I am web developer very new to the world of WPF so pardon this noob question. But whatever I try to return the image so far isnt helping. I can see that the byte array is being populated. But the Byte Array wont display in a browser, is there some conversion that I am missing ? Any hint or help will be highly appreciated.
I am posting this solution for anyone else who may be in the same scenario, OWIN Self Hosted App that serves images or other files.
I resolved this by adding this to the controller method
Image img = byteArrayToImage(buffer);
MemoryStream ms = new MemoryStream();
img.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
result.Content = new ByteArrayContent(ms.ToArray());
result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
return result;
public Image byteArrayToImage(byte[] byteArrayIn)
{
MemoryStream ms = new MemoryStream(byteArrayIn);
Image returnImage = Image.FromStream(ms);
return returnImage;
}

Categories

Resources