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

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

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.

Download a .zip file from database using C# Ado.net

I have a .zip file in the database (BLOB). I want to retrieve the same in my api. Please find below code snippet. I am able to download a zip file but not able to extract it. getting an error while extracting.
public IHttpActionResult GetDownloadLetter()
{
DownloadDocument docInfo = blogicObj.DownloadLetter();
var result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(docInfo.Document.GetBuffer())
};
result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
{
FileName = docInfo.DocumentName + ".zip"
};
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/zip");
var response = ResponseMessage(result);
return response;
}
public class DownloadDocument
{
public MemoryStream Document { get; set; }
public string DocumentType { get; set; }
public string DocumentName { get; set; }
}
public DownloadDocument DownloadDocument()
{
DownloadDocument letter = null;
try
{
letter = GetDummyDownload();
}
catch (Exception ex)
{
throw ex;
}
return letter;
}
public MemoryStream GetMemoryStream(SqlDataReader reader, int columnIndex)
{
using (MemoryStream stream = new MemoryStream())
{
long startIdx = 0;
byte[] buffer = new byte[256];
while (true)
{
long retBytes = reader.GetBytes(columnIndex, startIdx, buffer, 0, buffer.Length);
stream.Write(buffer, 0, (int)retBytes);
startIdx += retBytes;
if (retBytes != buffer.Length)
break;
}
return stream;
}
}
public DownloadDocument GetDummyDownload()
{
DownloadDocument letter = null;
string strQuery = "select * from [dbo].[documents] where id=1";
using (SqlConnection connection = new SqlConnection(connStr))
{
SqlCommand command = new SqlCommand(connStr);
command.CommandType = CommandType.Text;
command.CommandText = strQuery;
command.Connection = connection;
connection.Open();
SqlDataReader reader = command.ExecuteReader();
// Call Read before accessing data.
while (reader.Read())
{
letter = new DownloadDocument();
letter.Document = GetMemoryStream(reader, 4); //4 is for document column
letter.DocumentType = Convert.ToString(reader["DocumentType"]);
letter.DocumentName = Convert.ToString(reader["Name"]);
}
// Call Close when done reading.
reader.Close();
}
return letter;
}
Your C# application can use J# library to extract zip file. It's basically Java library:
using(var fis = new java.io.FileInputStream(FileName))
{
using(var zis = new java.util.zip.ZipInputStream(fis))
{
java.util.zip.ZipEntry ze;
while((ze = zis.getNextEntry()) != null)
{
if (ze.isDirectory())
continue;
Console.WriteLine("File name: " + ze.getName());
}
}
}
public IHttpActionResult GetDownloadLetter()
{
DownloadDocument docInfo = blogicObj.DownloadLetter();
var result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(docInfo.Document.ToArray())
};
result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
{
FileName = docInfo.DocumentName + ".zip"
};
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/zip");
var response = ResponseMessage(result);
return response;
}
public class DownloadDocument
{
public MemoryStream Document { get; set; }
public string DocumentType { get; set; }
public string DocumentName { get; set; }
}
public DownloadDocument DownloadDocument()
{
DownloadDocument letter = null;
try
{
letter = GetDummyDownload();
}
catch (Exception ex)
{
throw ex;
}
return letter;
}
public MemoryStream GetMemoryStream(SqlDataReader reader, int columnIndex)
{
byte[] buffer = (byte[])reader.GetValue(columnIndex);
MemoryStream stream = new MemoryStream(buffer);
return stream;
}
public DownloadDocument GetDummyDownload()
{
DownloadDocument letter = null;
string strQuery = "select * from [dbo].[documents] where id=1";
using (SqlConnection connection = new SqlConnection(connStr))
{
SqlCommand command = new SqlCommand(connStr);
command.CommandType = CommandType.Text;
command.CommandText = strQuery;
command.Connection = connection;
connection.Open();
SqlDataReader reader = command.ExecuteReader();
// Call Read before accessing data.
while (reader.Read())
{
letter = new DownloadDocument();
letter.Document = GetMemoryStream(reader, 4); //4 is for document column
letter.DocumentType = Convert.ToString(reader["DocumentType"]);
letter.DocumentName = Convert.ToString(reader["Name"]);
}
// Call Close when done reading.
reader.Close();
}
return letter;
}

Can't read image from SQL Server using C#

When I try to read images from my SQL Server database I get an error: on the following line:
Image returnImage = Image.FromStream(ms);
An unhandled exception of type 'System.ArgumentException' occurred in System.Drawing.dll
Additional information: Parameter is not valid.
My code:
public Image byteArrayToImage(byte[] byteArrayIn)
{
MemoryStream ms = new MemoryStream(byteArrayIn);
Image returnImage = Image.FromStream(ms);
return returnImage;
}
private ArrayList GetImagesFromDB(string code)
{
ArrayList images = new ArrayList();
SqlCommand selectImagesCommand = new SqlCommand("SELECT * FROM images WHERE code = '"+code+"'");
selectImagesCommand.Connection = myConnection;
if(myConnection.State == ConnectionState.Closed){
myConnection.Open();
}
SqlDataReader imagesReader = selectImagesCommand.ExecuteReader();
while (imagesReader.Read())
{
byte[] newimagebytesRecord = (byte[])imagesReader["image"];
images.Add(byteArrayToImage(newimagebytesRecord));
}
return images;
}
Use SqlDataReader.GetStream method.
So you would do something along the lines:
using(SqlDataReader imageReader = selectSingleImageCommand.ExecuteReader(CommandBehavior.SequentialAccess))
{
if (imageReader.Read())
{
using (Stream backendStream = imageReader.GetStream(0))
{
//Do whater you need with the Stream
}
}
}
You migh also be able to iterate over the reader (selecting multiple images) and open stream by stream - I haven't use it that way though, so I'm not 100% sure.
try
{
SqlCommand cmdSelect=new SqlCommand("select Picture" +
" from tblImgData where ID=#ID",this.sqlConnection1);
cmdSelect.Parameters.Add("#ID",SqlDbType.Int,4);
cmdSelect.Parameters["#ID"].Value=this.editID.Text;
this.sqlConnection1.Open();
byte[] barrImg=(byte[])cmdSelect.ExecuteScalar();
string strfn=Convert.ToString(DateTime.Now.ToFileTime());
FileStream fs=new FileStream(strfn,
FileMode.CreateNew, FileAccess.Write);
fs.Write(barrImg,0,barrImg.Length);
fs.Flush();
fs.Close();
pictureBox1.Image=Image.FromFile(strfn);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
this.sqlConnection1.Close();
}

Image isn't showing up in sql server database after sending image to it from MVC WCF service

I send the image from a Windows Phone 8 App to an MVC WCF service. I know it is receiving the image, because when it does receive the image, it is instructed to save the image in a local folder called "uploads". Every time the image gets there it is put into this folder so I can tell that it was uploaded. My trouble is with uploading it to my SQL Server database. Everything compiles, but when I check my database table, it is not there. Please help.
namespace MVCImageUpload.Controllers
{
public class FileUploadController : Controller
{
// GET: /FileUpload/
[HttpPost]
public ActionResult Index()
{
var fileUploaded = false;
foreach (string upload in Request.Files)
{
if (!HasFile(Request.Files[upload]))
continue;
string path = Path.Combine(
AppDomain.CurrentDomain.BaseDirectory,
"uploads");
string filename = Path.GetFileName(
Request.Files[upload].FileName);
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
Request.Files[upload].SaveAs(Path.Combine(
path, filename));
fileUploaded = true;
updatedata(filename);
}
this.ViewData.Add("uploaded", fileUploaded);
return View();
}
private static bool HasFile(HttpPostedFileBase file)
{
return (file != null && file.ContentLength > 0) ? true : false;
}
private void updatedata(string imagename)
{
//use filestream object to read the image.
//read to the full length of image to a byte array.
//add this byte as an oracle parameter and insert it into database.
try
{
//proceed only when the image has a valid path
if (imagename != "")
{
FileStream fs;
fs = new FileStream(#imagename, FileMode.Open, FileAccess.Read);
//a byte array to read the image
byte[] picbyte = new byte[fs.Length];
fs.Read(picbyte, 0, System.Convert.ToInt32(fs.Length));
fs.Close();
//open the database using odp.net and insert the data
string connstr = #".\SQLEXPRESS;Database=ImageDB;Trusted_Connection=True;";
SqlConnection conn = new SqlConnection(connstr);
conn.Open();
string query;
query = "insert into Images(ActualImage) values(#ActualImage)";
SqlParameter picparameter = new SqlParameter();
picparameter.SqlDbType = SqlDbType.Image;
picparameter.ParameterName = "ActualImage";
picparameter.Value = picbyte;
SqlCommand cmd = new SqlCommand(query, conn);
cmd.Parameters.Add(picparameter);
cmd.ExecuteNonQuery();
//MessageBox.Show("Image Added");
cmd.Dispose();
conn.Close();
conn.Dispose();
//Connection();
}
}
catch (Exception ex)
{
//MessageBox.Show(ex.Message);
}
}
}
}
You can skip a step and save the file directly into the database.
HttpPostedFileBase Picture = Request.Files["Picture"];
Byte[] Bytes = new byte[Picture.ContentLength];
string ContentType = Picture.ContentType;
string FileName = Picture.FileName;
Picture.InputStream.Read(Bytes, 0, Picture.ContentLength);
You now have Name, Bytes, and content type which u can store in the database.

showing image in gridview from byte array

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

Categories

Resources