如何将图像文件读取为byte[]?

发布于 2024-12-02 23:45:31 字数 484 浏览 1 评论 0原文

这就是我保存图像的方式。

[HttpPost]
public ActionResult Create(HttpPostedFileBase file)
{
    if (file != null)
    {
        var extension = Path.GetExtension(file.FileName);
        var fileName = Guid.NewGuid().ToString() + extension;
        var path = Path.Combine(Server.MapPath("~/Content/Photos"), fileName);
        file.SaveAs(path);

        //...
    }
}

我不想显示该位置的图像。我想先阅读它以进行进一步处理。

在这种情况下如何读取图像文件?

This is how I save images.

[HttpPost]
public ActionResult Create(HttpPostedFileBase file)
{
    if (file != null)
    {
        var extension = Path.GetExtension(file.FileName);
        var fileName = Guid.NewGuid().ToString() + extension;
        var path = Path.Combine(Server.MapPath("~/Content/Photos"), fileName);
        file.SaveAs(path);

        //...
    }
}

I don't want to display the image from that location. I want rather to read it first for further processing.

How do I read the image file in that case?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

南街女流氓 2024-12-09 23:45:31

更新:将图像读取到字节[]

// Load file meta data with FileInfo
FileInfo fileInfo = new FileInfo(path);

// The byte[] to save the data in
byte[] data = new byte[fileInfo.Length];

// Load a filestream and put its content into the byte[]
using (FileStream fs = fileInfo.OpenRead())
{
    fs.Read(data, 0, data.Length);
}

// Delete the temporary file
fileInfo.Delete();

// Post byte[] to database

为了历史的缘故,这是我在问题澄清之前的回答。

您的意思是将其加载为 BitMap 实例?

 BitMap image = new BitMap(path);

 // Do some processing
 for(int x = 0; x < image.Width; x++)
 {
     for(int y = 0; y < image.Height; y++)
     {
         Color pixelColor = image.GetPixel(x, y);
         Color newColor = Color.FromArgb(pixelColor.R, 0, 0);
         image.SetPixel(x, y, newColor);
     }
 }

// Save it again with a different name
image.Save(newPath);

Update: Reading the image to a byte[]

// Load file meta data with FileInfo
FileInfo fileInfo = new FileInfo(path);

// The byte[] to save the data in
byte[] data = new byte[fileInfo.Length];

// Load a filestream and put its content into the byte[]
using (FileStream fs = fileInfo.OpenRead())
{
    fs.Read(data, 0, data.Length);
}

// Delete the temporary file
fileInfo.Delete();

// Post byte[] to database

For history's sake, here's my answer before the question was clarified.

Do you mean loading it as a BitMap instance?

 BitMap image = new BitMap(path);

 // Do some processing
 for(int x = 0; x < image.Width; x++)
 {
     for(int y = 0; y < image.Height; y++)
     {
         Color pixelColor = image.GetPixel(x, y);
         Color newColor = Color.FromArgb(pixelColor.R, 0, 0);
         image.SetPixel(x, y, newColor);
     }
 }

// Save it again with a different name
image.Save(newPath);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文