ali kiani
ali kiani

Reputation: 887

How Convert Image To byte[]?

I want to sent my image through network with TcpClient and NetworkStream.

type of image is (System.Windows.Controls.Image)

now how i can convert my image to bytes ?

thanks.

Upvotes: 1

Views: 149

Answers (3)

Nik
Nik

Reputation: 472

I would suggest convert image to PNG format as i have experienced many issues because of JPEG. Try the below code

 byte[] b1=null;
 ByteArrayOutputStream baos=new ByteArrayOutputStream();
 ImageIO.write(img, "png", baos);
 b1=baos.toByteArray();

Upvotes: 0

Mahesh Chitroda
Mahesh Chitroda

Reputation: 178

Hope Below Code Help You.if you allow user to upload image.

 FileStream fs;
 fs = new FileStream(OpenImage.FileName, FileMode.Open, FileAccess.Read);
 byte[] picByte;
 picByte = new byte[Convert.ToInt32(fs.Length)];
 fs.Read(picByte, 0, Convert.ToInt32(fs.Length));
 fs.Close();

Here OpenImage is a OpenFileDialog Control.

Upvotes: 0

Newton Sheikh
Newton Sheikh

Reputation: 1396

you will have to serialize your image in order to send it via Network.

Image im = Image.FromFile(@"C:\hello.jpg");
MemoryStream ms = new MemoryStream();
im.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] Barray = ms.ToArray();

string str = string.Empty;
foreach (byte b in oImage)
{
    str += b.ToString();
}

Upvotes: 1

Related Questions