I've got a byte array for an image (stored in the database). I want to create an Image object, create several Images of different sizes and store them back in the database (save it back to a byte array).
I'm not worried about the database part, or the resizing. But is there an easy way to load an Image object without saving the file to the file system, and then put it back in a byte array when I'm done resizing it? I'd like to do it all in memory if I can.
Something like:
Image myImage = new Image(byte[]);
or
myImage.Load(byte[]);
To convert a byte array to an image. Create a ByteArrayInputStream object by passing the byte array (that is to be converted) to its constructor. Read the image using the read() method of the ImageIO class (by passing the ByteArrayInputStream objects to it as a parameter).
Read the image using the read() method of the ImageIO class. Create a ByteArrayOutputStream object. Write the image to the ByteArrayOutputStream object created above using the write() method of the ImageIO class. Finally convert the contents of the ByteArrayOutputStream to a byte array using the toByteArray() method.
Images are binary data - this is easily represented as byte arrays. The image in the sample is stored in the database as a BLOB - not a string or location, that is, it is binary data.
Use the default CommonsMultipartFile where you to use the FileDiskItem object to create it. Example: FileItem fileItem = new DiskFileItem("fileData", "application/pdf",true, outputFile. getName(), 100000000, new java.
You'd use a MemoryStream to do this:
byte[] bytes;
...
using (var ms = new System.IO.MemoryStream(bytes)) {
using(var img = Image.FromStream(ms)) {
...
}
}
Based on your comments to another answer, you can try this for performing a transformation on an image that's stored in a byte[]
then returning the result as another byte[]
.
public byte[] TransformImage(byte[] imageData)
{
using(var input = new MemoryStream(imageData))
{
using(Image img = Image.FromStream(input))
{
// perform your transformations
using(var output = new MemoryStream())
{
img.Save(output, ImageFormat.Bmp);
return output.ToArray();
}
}
}
}
This will allow you to pass in the byte[]
stored in the database, perform whatever transformations you need to, then return a new byte[]
that can be stored back in the database.
Only answering the first half of the question: Here's a one-liner solution that works fine for me with a byte array that contains an image of a JPEG file.
Image x = (Bitmap)((new ImageConverter()).ConvertFrom(jpegByteArray));
EDIT: And here's a slightly more advanced solution: https://stackoverflow.com/a/16576471/253938
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With