2011-06-02 30 views
0

我遇到問題。當圖像保存在我的數據庫中時,它們將與文件字節一起保存,並且此記錄具有參考ID。有一個.ashx文件將採用此參考ID號並獲取文件信息/文件字節並顯示圖像或允許下載圖像。操縱文件字節時的圖像轉換

img src="/download.ashx?id=THEREFID 

這將在頁面上顯示圖像。如果我只是鏈接到.ashx頁面,它會下載圖像。這可以。然而,我的一些圖像保存爲.TIF,我需要將它們轉換爲.jpeg。

我有一個名爲的FileData

public string FileName; 
public byte[] theData; 
public long FileSizeBytes; 
public string MIME; 
public string Extension; 

類在我.ashx的頁面我有一個加載上面的FileData類的方法。然後用HttpContext類沿的FileData類被髮送到一個方法:

private void Process(HttpContext context, FileData file) 
{ 
    context.Response.ContentTYpe = file.MIME; 
    context.Response.AddHeader("Content-Disposition", "attachment; filename=" 
     + file.FileName.Replace(' ', '_') 
     + file.FileExtension); 
    context.Response.AddHeader("Content-Length", file.FileSizeBytes.ToString()); 
    context.Response.Expires = 0; 
    context.Response.BinaryWrite(file.Data); 
    context.ApplicationInstance.CompleteRequest(); 
} 

我需要找到一種方法,這種信息轉換爲JPEG。我想也許是一個臨時位圖,將其轉換爲.jpeg,然後從這裏獲取文件字節?

回答

0

我會做它,你打算......

或多或少這樣的:

   System.Drawing.Bitmap tiffImage; 
       using(BinaryWriter baseWriter = new BinaryWriter(new MemoryStream())) 
       { 
        baseWriter.Write(tiffData); 
        baseWriter.BaseStream.Position = 0; 
        tiffImage = new System.Drawing.Bitmap(baseWriter.BaseStream); 
       } 

       MemoryStream jpgStream = new MemoryStream(); 

       tiffImage.Save(jpgStream, System.Drawing.Imaging.ImageFormat.Jpeg); 
       jpgStream.Position = 0; 
       using (BinaryReader br = new BinaryReader(jpgStream)) 
       { 
        context.Response.BinaryWrite(br.ReadBytes(jpgStream.Length)); 
       } 
0

我想通了。這是我做的:

Image img = Image.FromStream(new MemoryStream(file.Data)); 
Bitmap bmp = (Bitmap)img; 

EncoderParameters encoderParams = new EncoderParameters(); 
encoderParams.Param[0] = new EncoderParameter(Encoder.Quality, 50L); 

ImageCodecInfo codecInfo = GetEncoderInfo("image.jpeg"); 
MemoryStream newImage = new MemoryStream(); 

bmp.Save(newImage, codecInfo, encoderParams); 

byte[] newData = newImage.ToArray(); 

//Overwritting the original FileData 
file.Data = newData; 
file.FileSizeBytes = newData.Length; 
file.MIME = "image/jpeg";