We help IT Professionals succeed at work.

Image data type in C#

Aquarus
Aquarus asked
on
In DataLayer of my project I use the following template to pass the recordset data from SP to the Apllication:
[DataContractAttribute]
        public class ClassDetail
        {
            public ClassDetail(IR_USP_SPResult detail)
            {
                this.PBT = detail.PBT;
            }

            [DataMember]
            private string  PBT  { get; set; }
        }

DataMember define the fieldname datatype from the Select statement of the Storeprocedure  with the name IR_USP_SPResult .

I have to create something similar for the select statement of the stored procedure that returns only one field from the table and the datatype of this field is image.

I have already tried
using System.Drawing at the top of my project and this addition allowed me to do the part of the template like this:
 [DataMember]
            private Image  PBT  { get; set; }

But on the step where I am assigning the outside data to the internal:
public ClassDetail(IR_USP_SPResult detail)
            {
                this.PBT = detail.PBT;
            }
I see the red line under detail.PBT and it says that I cannot assign image type to the binary type. What am I doing wrong?
Comment
Watch Question

Sr. Architect
Commented:
The image data type in Sql Server is treated as binary data in .Net, so you need to first convert it to byte array before use. In case you want to load the image from db use something like:

Byte[] imgBytes = (Byte[]) ds.Tables[0].Rows[0][0];
IO.MemoryStream ms = new IO.MemoryStream(imgBytes);
PictureBox1.Image = Image.FromStream(ms);

-Rahul
Convert IR_USP_SPResult class's PBT variable as image datatype.

My suggestion is never store image itself in database. Instead have the image in your application or some common folder and save the file path as string in table. That would be faster and less error prone.



Author

Commented:
This is what I have - SQL side and C#.  Where this conversion you suggest have to happen?

I. SQL SIDE:

I.1 TABLE:

CREATE TABLE [dbo].[IR_TBL_ACCTable](
      [int_UnitID] [int] IDENTITY(1,1) NOT NULL,
      [img_Report] [image] NULL
      
 ON [PRIMARY]
 

I.2 STORED PROCEDURE name: IR_USP_INVSP:

SELECT img_Report 'InvoiceReport'
      FROM IR_TBL_ACCInvoice
      WHERE int_UnitID = @iParameter

II. C#:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.IO;
using System.Drawing;

public class ClassDetail
        {

            public ClassDetail(IR_USP_INVSPResult detail)
            {
                this.InvoiceReport = detail.InvoiceReport;
            }

            [DataMember]
            private Image InvoiceReport { get; set; }
           
        }

Explore More ContentExplore courses, solutions, and other research materials related to this topic.