Can anyone please tell me how an image(.jpg,.gif,.bmp) is converted into a byte array ?
The easiest way to convert an image to bytes is to use the ImageConverter class under the System.Drawing namespace
public static byte[] ImageToByte(Image img)
{
ImageConverter converter = new ImageConverter();
return (byte[])converter.ConvertTo(img, typeof(byte[]));
}
I've assumed what you want is the pixel values. Assuming bitmap is a System.Windows.Media.Imaging.BitmapSource:
int stride = bitmap.PixelWidth * ((bitmap.Format.BitsPerPixel + 7) / 8);
byte[] bmpPixels = new byte[bitmap.PixelHeight * stride];
bitmap.CopyPixels(bmpPixels, stride, 0);
Note that the 'stride' is the number of bytes required for each row of pixel ddata. Some more explanation available here.
If your image is already in the form of a System.Drawing.Image, then you can do something like this:
public byte[] convertImageToByteArray(System.Drawing.Image image)
{
using (MemoryStream ms = new MemoryStream())
{
image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
// or whatever output format you like
return ms.ToArray();
}
}
You would use this function with the image in your picture box control like this:
byte[] imageBytes = convertImageToByteArray(pictureBox1.Image);
to get the bytes from any file try:
byte[] bytes = File.ReadAllBytes(pathToFile);
Based off of MusiGenesis; helped me a lot but I had many image types. This will save any image type that it can read.
System.Drawing.Imaging.ImageFormat ImageFormat = imageToConvert.RawFormat;
byte[] Ret;
try
{
using (MemoryStream ms = new MemoryStream())
{
imageToConvert.Save(ms, ImageFormat);
Ret = ms.ToArray();
}
}
catch (Exception) { throw; }
return Ret;
You can use File.ReadAllBytes method to get bytes
If you are using FileUpload class then you can use FileBytes Property to get the Bytes as Byte Array.
Related
I am trying to use the ImageConverter class in my ASP.NET Core project to convert an Image to a byte[], but I can't seem to find the class.
I have installed the System.Drawing.Common package, but still can't find it.
I am using .NET Core 3.1.
If on .NET Core 3.1, ImageConverter requires the System.Windows.Extensions package:
https://learn.microsoft.com/en-us/dotnet/api/system.drawing.imageconverter?view=netcore-3.1
In .NET 5 it is included in System.Drawing.Common:
https://learn.microsoft.com/en-us/dotnet/api/system.drawing.imageconverter?view=net-5.0
You can convert image to byte easily.
protected virtual byte[] LoadPictureFromFile(string filePath)
{
if (!File.Exists(filePath))
return new byte[0];
return File.ReadAllBytes(filePath);
}
Extra help..
public byte[] ResizeImage(byte[] pictureBinary,int newWidth, int newHeight)
{
byte[] pictureBinaryResized;
using (var stream = new MemoryStream(pictureBinary))
{
Bitmap b = null;
try
{
//try-catch to ensure that picture binary is really OK. Otherwise, we can get "Parameter is not valid" exception if binary is corrupted for some reasons
b = new Bitmap(stream);
}
catch (ArgumentException exc)
{
// log error
}
if (b == null)
{
//bitmap could not be loaded for some reasons
return new byte[0];
}
using (var destStream = new MemoryStream())
{
ImageBuilder.Current.Build(b, destStream, new ResizeSettings
{
Width = newWidth,
Height = newHeight,
Scale = ScaleMode.Both,
Quality = _mediaSettings.DefaultImageQuality
});
pictureBinaryResized = destStream.ToArray();
b.Dispose();
}
}
return pictureBinaryResized;
}
Instead of ImageConverter, you can trying to look at this for speed up:
Save bitmap to stream:
bitmap.save(stream);
Or open image file:
FileStream stream = new FileStream(imageFilePath, FileMode.Open, FileAccess.Read);
Then simply use Stream2Bytes:
byte[] OO7b = Stream2Bytes(stream);
And this is the Stream2Bytes method:
public byte[] Stream2Bytes(Stream stream, int chunkSize = 1024)
{
if (stream == null)
{
throw new System.ArgumentException("Parameter cannot be null", "stream");
}
if (chunkSize < 1)
{
throw new System.ArgumentException("Parameter must be greater than zero", "chunkSize");
}
if (chunkSize > 1024 * 64)
{
throw new System.ArgumentException(String.Format("Parameter must be less or equal {0}", 1024 * 64), "chunkSize");
}
List<byte> buffers = new List<byte>();
using (BinaryReader br = new BinaryReader(stream))
{
byte[] chunk = br.ReadBytes(chunkSize);
while (chunk.Length > 0)
{
buffers.AddRange(chunk);
chunk = br.ReadBytes(chunkSize);
}
}
return buffers.ToArray();
}
I am using MVC4. My requirement is:
I have to convert the file into byte array and save to database varbinary column.
For this I written code like below:
public byte[] Doc { get; set; }
Document.Doc = GetFilesBytes(PostedFile);
public static byte[] GetFilesBytes(HttpPostedFileBase file)
{
MemoryStream target = new MemoryStream();
file.InputStream.CopyTo(target);
return target.ToArray();
}
I am downloading the file by using the following code:
public ActionResult Download(int id)
{
List<Document> Documents = new List<Document>();
using (SchedulingServiceInstanceManager facade = new SchedulingServiceInstanceManager("SchedulingServiceWsHttpEndPoint"))
{
Document Document = new Document();
Document.DMLType = Constant.DMLTYPE_SELECT;
Documents = facade.GetDocuments(Document);
}
var file = Documents.FirstOrDefault(f => f.DocumentID == id);
return File(file.Doc.ToArray(), "application/octet-stream", file.Name);
}
when I am downloading pdf file then it is showing message as "There was an error opening this document. The file is damaged and could not be repaired."
Any thing else I need to do?
I tried with the following code but no luck
return File(file.Doc.ToArray(), "application/pdf", file.Name);
Please help me to solve the issue.
Thanks in advance.
Please try as in below code in your controller
FileStream stream = File.OpenRead(#"c:\path\to\your\file\here.txt");
byte[] fileBytes= new byte[stream.Length];
stream.Read(fileBytes, 0, fileBytes.Length);
stream.Close();
//Begins the process of writing the byte array back to a file
using (Stream file = File.OpenWrite(#"c:\path\to\your\file\here.txt"))
{
file.Write(fileBytes, 0, fileBytes.Length);
}
It may helps you...
using wcf/wcf web services to upload a images give me with example?
In my project i want to upload image by using WCF
Basically you should use WCF streaming.
[ServiceContract]
public interface ITransferService
{
[OperationContract]
void UploadFile(RemoteFileInfo request);
}
public void UploadFile(RemoteFileInfo request)
{
FileStream targetStream = null;
Stream sourceStream = request.FileByteStream;
string uploadFolder = #"C:\\upload\\";
string filePath = Path.Combine(uploadFolder, request.FileName);
using (targetStream = new FileStream(filePath, FileMode.Create,
FileAccess.Write, FileShare.None))
{
//read from the input stream in 65000 byte chunks
const int bufferLen = 65000;
byte[] buffer = new byte[bufferLen];
int count = 0;
while ((count = sourceStream.Read(buffer, 0, bufferLen)) > 0)
{
// save to output stream
targetStream.Write(buffer, 0, count);
}
targetStream.Close();
sourceStream.Close();
}
}
The easiest way is to convert the image to a byte array before sending it, and then converting it back to an image on the destination site.
Here are two methods for doing just that:
public byte[] ImageToByteArray( Image image)
{
var ms = new MemoryStream();
image.Save(ms, ImageFormat.Png);
return ms.ToArray();
}
public static Image ByteArrayToImage(byte[] byteArray)
{
var ms = new MemoryStream(byteArray);
return Image.FromStream(ms);
}
That means your web service can have a method something like this:
public void UploadImage( byte[] imageData )
{
var image = ByteArrayToImage( imageData );
//save image to disk here, or do whatever you like with it
}
i have a column were i want the image to come out but at run-time only the name appears
MIMEType: image/jpeg Source: Database Value: =Fields!Image.Value
i saw this code but idk were to put it:
MemoryStream ms = new MemoryStream();
Image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
return ms.ToArray();
please help
Do something like
Bitmap _img = new Bitmap(10, 10);
public byte[] MyPicture
{
get
{
// Generate bitmap
// Convert to stream
MemoryStream ms = new MemoryStream();
__img.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
return ms.ToArray();
}
}
can any one has idea. how to convert BitmapImage to Byte[] in silverlight4 application
i have one image file in .xap file.
BitmapImage bi = new BitmapImage(new Uri("images/GRed.png", UriKind.Relative));
now i want to convert BitmapImage to Byte[] and save in to db as binary format.
private byte[] ToByteArray(BitmapImage bi)
{
WriteableBitmap bmp = new WriteableBitmap(bi);
int[] p = bmp.Pixels;
int len = p.Length * 4;
byte[] result = new byte[len];
Buffer.BlockCopy(p, 0, result, 0, len);
return result;
}