开发者

how to convert image into bytes [] in c#

this will be a noob question. I'm new to c#

I have a file upload server control that I am using to save images to server.

I have, in my library, an image resize fu开发者_如何学Cnction with this parameter:

byte[] resizeImage(byte[] image, int witdh)

that i am supposed to use. now, i am saving my file to some path as upImage.saveas("filepath");

ok?

now, I want to resize this image and i cant figure how to convert that image to bytes???

where is the article to convert? everywhere i see, i can only see bytes to image but i want other way around..

please help?


Do you mean convert the saved file to a byte[] array? If so, you can use File.ReadAllBytes:

byte[] imageBytes = File.ReadAllBytes("example.jpg");

If you want to grab the byte[] array directly from your FileUpload control then you can use the FileBytes property:

byte[] imageBytes = yourUploadControl.FileBytes;


Looks like you can save it to a MemoryStream then convert the MemoryStream to a byte array. From here

public byte[] imageToByteArray(System.Drawing.Image imageIn)
{
 MemoryStream ms = new MemoryStream();
 imageIn.Save(ms,System.Drawing.Imaging.ImageFormat.Gif);
 return  ms.ToArray
}


convert the file to bytes in fileuploadcontrol on post method

public ActionResult ServiceCenterPost(ServiceCenterPost model)
{
     foreach (var file in model.FileUpload)
     {
          if (file != null && file.ContentLength > 0)
          {
             byte[] fileBytes = new byte[file.ContentLength];
             file.InputStream.Read(fileBytes, 0, Convert.ToInt32(file.ContentLength));
             string thumbpath = _fileStorageService.GetPath(fileName);
            _fileStorageService.SaveFile(thumbpath, fileBytes);
         }
     }
}


Well, the short answer is

File.ReadAllBytes("filepath");

But the long answer is, it doesn't sound like you have any idea what's going on, so I suggest you make sure that the image is actually encoded the way you think it is (Is it actually a bitmap on disk, or is it compressed? What does resizeImage actually do with the bytes and what kind of image does it expect? Why doesn't resizeImage take an Image and just resize it with GDI+?) Otherwise you might be in for a surprise.


You can use the Image.Save function, passing in a memory stream. Once it completes, you can use MemoryStream.Read or MemoryStream.ToArray to recover the bytes.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜