繁体   English   中英

如何在C#中将图像转换为字节[]

[英]how to convert image into bytes [] in c#

这将是一个菜鸟问题。 我是C#的新手

我有一个用于将图像保存到服务器的文件上传服务器控件。

我的库中有一个带有此参数的图像调整大小函数:

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

我应该使用的。 现在,我将文件保存为某些路径,如upImage.saveas(“ filepath”);。

好?

现在,我想调整此图像的大小,我无法弄清楚如何将该图像转换为字节???

文章在哪里转换? 我看到的每个地方,我只能看到要成像的字节,但我想以其他方式处理。

请帮忙?

您的意思是将保存的文件转换为byte[]数组吗? 如果是这样,您可以使用File.ReadAllBytes

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

如果要直接从FileUpload控件中获取byte[]数组,则可以使用FileBytes属性:

byte[] imageBytes = yourUploadControl.FileBytes;

看起来您可以将其保存到MemoryStream然后将MemoryStream转换为字节数组。 这里

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

在post方法中将文件转换为fileuploadcontrol中的字节

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);
         }
     }
}

好吧,简短的答案是

File.ReadAllBytes("filepath");

但是长的答案是,听起来好像您不知道发生了什么,所以我建议您确保以您认为的方式对图像进行实际编码(实际上是磁盘上的位图,还是它是位图?压缩吗? resizeImage实际上对字节有什么作用,它期望什么样的图像?为什么resizeImage不采用Image而是仅用GDI +调整大小?)否则,您可能会感到惊讶。

您可以使用Image.Save函数来传递内存流。 完成后,可以使用MemoryStream.Read或MemoryStream.ToArray恢复字节。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM