从/向流而不是磁盘保存/加载图像

时间:2009-11-19 19:47:40

标签: asp.net image

我有以下代码从数据库中获取一个未正确保存的Image将其转换为Jpeg并以字节数组返回Image;

    public Byte[] GetImageFromDB(int id)
    {
        var imageData = _repository.GetImage(id);
        var newImageData = ConvertCorruptedImage(imageData, id);
        return newImageData;
    }

    private byte[] ConvertCorruptedImage(byte[] imageData, int id)
    {
        // Save DB Image as a file. 
        MemoryStream img = new MemoryStream(imageData);
        var saveDBImage = Image.FromStream(img);


        string originalFileName = @"c:\original_" + id.ToString() + ".jpg";
        string newFileName = @"C:\new" + id.ToString() + ".jpg";

        // Delete if already Exists
        DeleteImageFile(originalFileName);

        saveDBImage.Save(originalFileName);


        // Read Saved DB Image From Saved File & Save as jpeg
        Bitmap bm = new Bitmap(originalFileName);
        bm.Save(newFileName , ImageFormat.Jpeg);

        // Return Converted JPEG Image
        var newImage = ImageToByte(Image.FromFile(newFileName));

        //DeleteCreatedImage(newFileName);
        //DeleteCreatedImage(originalFileName);

        return newImage;
    }


    private byte[] ImageToByte(Image img)
    {
        ImageConverter converter = new ImageConverter();
        return (byte[])converter.ConvertTo(img, typeof(byte[]));
    }

    public static void DeleteImageFile(string fileName)
    {
        FileInfo file = new FileInfo(fileName);
        if (file.Exists && !file.IsReadOnly)
        {
            System.IO.File.Delete(fileName);
        }
    }

我想知道是否有办法在不将文件保存到硬盘的情况下执行此操作,或者如果我保存它,则在完成后将其删除。

我尝试为每个图片添加一个删除(检查ConvertCorruptedImage方法的注释掉部分),但我不断收到以下错误:

The process cannot access the file 'C:\new_xx.jpg' because it is being used by another process.

我真的不想将图像保存到硬盘上。

提前致谢

3 个答案:

答案 0 :(得分:2)

的内容
var image = Image.FromStream(new MemoryStream(imageData));
            Bitmap bmp = new Bitmap(image);
            MemoryStream outStream = new MemoryStream();
            bmp.Save(outStream,ImageFormat.Jpeg);
            return outStream.ToArray();

答案 1 :(得分:1)

使用写入Stream的Bitmap.Save重载。

var stream = new MemoryStream();
bm.Save(stream, ImageFormat.Jpeg);

答案 2 :(得分:1)

您可以直接从MemoryStream

加载位图
Bitmap bm = new Bitmap(imgStream);

您还可以将位图保存到流:

MemoryStream newImgStream = new MemoryStream();
bm.Save(newMemoryStream, ImageFormat.Jpeg);