2012-01-04 20 views
0

我有一個ASP圖像控件我想保存到特定的文件夾。將ASP圖像控件導出到文件夾

Image1.ImageUrl = "~/fa/barcode.aspx?d=" + Label1.Text.ToUpper(); 

這基本上就是barcode.aspx做:

Bitmap oBitmap = new Bitmap(w, 100); 

     // then create a Graphic object for the bitmap we just created. 
     Graphics oGraphics = Graphics.FromImage(oBitmap); 

     oGraphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.None; 
     oGraphics.TextRenderingHint = TextRenderingHint.SingleBitPerPixel; 


     // Let's create the Point and Brushes for the barcode 
     PointF oPoint = new PointF(2f, 2f); 
     SolidBrush oBrushWrite = new SolidBrush(Color.Black); 
     SolidBrush oBrush = new SolidBrush(Color.White); 

     // Now lets create the actual barcode image 
     // with a rectangle filled with white color 
     oGraphics.FillRectangle(oBrush, 0, 0, w, 100); 

     // We have to put prefix and sufix of an asterisk (*), 
     // in order to be a valid barcode 
     oGraphics.DrawString("*" + Code + "*", oFont, oBrushWrite, oPoint); 
Response.ContentType = "image/jpeg"; 
oBitmap.Save(Response.OutputStream, ImageFormat.Jpeg); 

如何將其保存到一個文件夾(〜/ FA/barcodeimages/)?到目前爲止,這是我的嘗試:

WebClient webClient = new WebClient(); 
       string remote = "http://" + Request.Url.Authority.ToString() + "/fa/barcode.aspx?d=" + Label1.Text.ToUpper(); 
       string local = Server.MapPath("barcodeimages/" + Label1.Text.ToUpper() + ".jpeg"); 
       webClient.DownloadFile(remote, local); 

但它不起作用,我總是得到一個損壞的.jpeg文件。而且它似乎效率低下。

+0

你沒有解釋'oBitmap'來自哪裏 - 或者你真正想要「保存」一個圖像控件。圖像數據本身在哪裏,你想要保存什麼? – 2012-01-04 07:13:44

+0

@JonSkeet它實際上是一個條形碼圖像。我編輯帖子以包含代碼。我想要做的是複製/導出圖像到我的網站的文件夾。所以結果會在網站文件夾中有一個文件:(〜/ fa/barcodeimages/barcode1.jpeg)。 – 2012-01-04 07:19:51

+0

@PodMays:如果您在瀏覽器中輸入網址,它是否呈現jpeg?如果不是,則問題在於位圖構造的方式。 – shahkalpesh 2012-01-04 08:12:34

回答

1

看起來問題在於您的業務邏輯 - 生成條形碼圖像所需的代碼 - 位於錯誤的位置。

你應該保持業務邏輯遠離你的aspx頁面(這是關於服務的圖像的URL響應)的呈現邏輯,並移動Bitmap創建邏輯的地方,無論是「服務條形碼「和」保存條形碼到磁盤「代碼可以得到它。這可能在不同的業務邏輯組件中,也可能只是在同一個項目中的一個單獨的類中。主要的是你想在可重用的地方。

在這一點上,你的aspx代碼更改爲類似:

Response.ContentType = "image/jpeg"; 
using (Bitmap bitmap = barcodeGenerator.Generate(Code)) 
{ 
    bitmap.Save(Response.OutputStream, ImageFormat.Jpeg); 
} 

和你節省代碼更改爲類似:

// TODO: Validate that the text here doesn't contain dots, slashes etc 
string code = Label1.Text.ToUpper(); 
string file = Server.MapPath("barcodeimages/" + code + ".jpeg"); 
using (Bitmap bitmap = barcodeGenerator.Generate(code)) 
{ 
    bitmap.Save(file, ImageFormat.Jpeg); 
} 

這裏,barcodeGenerator將理想的一個depedency注入實例你的BarcodeGenerator課程(或其他任何事情)。如果你不使用依賴注入,你可以直接創建一個新的實例,每次指定字體等 - 它不是很愉快,但它應該工作正常。

+0

嗨,條形碼生成代碼實際上是在Barcode.aspx(Page_Load)。我用'Image1.ImageUrl =「〜/ fixedasset/GenerateBarcodeImage.aspx?d =」+ Label1.Text.ToUpper();'on(Page1.aspx)來調用它。 – 2012-01-08 14:44:33

+0

@PodMays:但是,這是我的觀點 - 它會更好*不*要在表示層。 – 2012-01-08 15:24:58