我有以下代碼它接受一個正確保存圖像從數據庫將其轉換爲JPEG,並返回一個字節數組的圖像;保存/載入圖像
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.
我真的不希望保存圖像到硬盤。
在此先感謝
謝謝!這完美的作品! – zSynopsis