2009-09-03 65 views
8

Tengo una imagen (en formato .png) y quiero que esta imagen se convierta en binaria.¿Convertir imagen a binario?

¿Cómo se puede hacer esto con C#?

+2

¿Qué quiere decir 'convertir a binario'? ¿Te refieres, por ejemplo, en blanco y negro? – pavium

+1

¿Podría explicarlo un poco más? Una imagen ya es binaria. ¿Desea que se descomprima? ¿Desea acceder a los píxeles? –

+0

Tengo que escribir los datos binarios de la imagen en la pantalla usando Response.BinaryWrite(); – Martijn

Respuesta

6

Puesto que usted tiene un uso fichero: -

Response.ContentType = "image/png"; 
Response.WriteFile(physicalPathOfPngFile); 
+0

Cómo convertirla de nuevo a ¿imagen? –

20
byte[] b = File.ReadAllBytes(file); 

File.ReadAllBytes Method

abre un archivo binario, lee los contenido del archivo en un byte matriz, y luego cierra el archivo.

+1

A menos que haya alguna necesidad de procesar esa matriz antes de enviarla a la respuesta, también puede dejar que ASP.NET la maneje usando WriteFile – AnthonyWJones

11

Prueba esto:

Byte[] result 
    = (Byte[])new ImageConverter().ConvertTo(yourImage, typeof(Byte[])); 
3

que podría hacer:

MemoryStream stream = new MemoryStream(); 
    image.Save(stream, ImageFormat.Png); 
    BinaryReader streamreader = new BinaryReader(stream); 

    byte[] data = streamreader.ReadBytes(stream.Length); 

datos contendría entonces el contenido de la imagen.

+0

¿Qué tipo de datos tiene la imagen? Estoy usando Webforms ... – Martijn

+0

System.Drawing.Image – Kazar

0

Primero, convierta la imagen en una matriz de bytes usando la clase ImageConverter. Luego, especifique el mime type de su imagen png, y ¡listo!

He aquí un ejemplo:

TypeConverter tc = TypeDescriptor.GetConverter(typeof(Byte[])); 
Response.ContentType = "image/png"; 
Response.BinaryWrite((Byte[])tc.ConvertTo(img,tc)); 
0
System.Drawing.Image image = System.Drawing.Image.FromFile("filename"); 
byte[] buffer; 
MemoryStream stream = new MemoryStream(); 
image.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg); 

buffer = stream.ToArray(); // converted to byte array 
stream = new MemoryStream(); 
stream.Read(buffer, 0, buffer.Length); 
stream.Seek(0, SeekOrigin.Begin); 
System.Drawing.Image img = System.Drawing.Image.FromStream(stream); 
+0

sí, gracias. corregido! –

0
public static byte[] ImageToBinary(string imagePath) 
    { 
     FileStream fS = new FileStream(imagePath, FileMode.Open, FileAccess.Read); 
     byte[] b = new byte[fS.Length]; 
     fS.Read(b, 0, (int)fS.Length); 
     fS.Close(); 
     return b; 
    } 

sólo tiene que utilizar el código anterior Creo que su problema será resuelto

0
using System.IO; 

FileStream fs=new FileStream(Path, FileMode.Open, FileAccess.Read); //Path is image location 
Byte[] bindata= new byte[Convert.ToInt32(fs.Length)]; 
fs.Read(bindata, 0, Convert.ToInt32(fs.Length)); 
Cuestiones relacionadas