开发者

Saving/Loading Images from/to stream instead of a disk

I have the following code which takes an improperly saved Image from the database converts it to a Jpeg and returns the Image in a byte array;

    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 = ImageTo开发者_如何学编程Byte(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);
        }
    }

I was wondering if there was a way to do this without saving a file to the hard disk or if i do save it then deleting it once i am done with it.

I've tried adding a delete for each images (check the commented out portion of the ConvertCorruptedImage method) but i keep getting the following error:

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

I really don't want to be saving images to a hard disk.

Thanks in advance


something along the lines of

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


Use the overload of Bitmap.Save that writes to a Stream.

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


You can load the bitmap directly from your MemoryStream:

Bitmap bm = new Bitmap(imgStream);

You can also save the bitmap to a stream:

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜