导出ASP图像控件到一个文件夹

本文关键字:一个 文件夹 ASP 图像 控件 导出 | 更新日期: 2023-09-27 18:19:19

我有一个ASP图像控件,我想保存到一个特定的文件夹。

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

这基本上就是条形码。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文件。

导出ASP图像控件到一个文件夹

问题似乎是您的业务逻辑——生成条形码图像所需的代码——放在了错误的位置。

您应该使业务逻辑远离aspx页面的表示逻辑(这是关于提供图像以响应URL),并将Bitmap创建逻辑移动到"服务条形码"answers"将条形码保存到磁盘"代码都可以获得的地方。它可以位于不同的业务逻辑组装中,也可以位于同一项目中的单独类中。最重要的是你要把它放在一个可重复使用的地方。

此时,您的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);
}

在这里,理想情况下,barcodeGeneratorBarcodeGenerator类的依赖注入实例(或任何结果)。如果你不使用依赖注入,你可以直接创建一个新实例,每次指定字体等——这不是那么令人愉快,但应该可以正常工作。