簡體   English   中英

無法在ASP.NET C#項目中保存條形碼生成的圖像

[英]Can't save image for barcode generation in ASP.NET C# project

我正在嘗試使用System.Drawing.Save()保存圖像,並且我一直收到無效參數異常。

有人可以看看我的代碼並告訴我我做錯了什么。

這是生成條形碼圖像的代碼。

 public class BarcodeHelper
    {
        Font barcodeFont;
        public BarcodeHelper()
        {
             PrivateFontCollection fonts;
             FontFamily family = LoadFontFamily("~/../fonts/Code128bWin.ttf", out fonts);   
             barcodeFont = new Font(family, 20.0f);   

            // when done:   
            barcodeFont.Dispose();   
            family.Dispose();   
            family.Dispose();
        }
        public FontFamily LoadFontFamily(string fileName, out PrivateFontCollection fontCollection) 
        { 
            fontCollection = new PrivateFontCollection(); 
            fontCollection.AddFontFile(fileName); 
            return fontCollection.Families[0]; 
        }

        public Image GenerateBarcode(string barcodeText) 
        {
            Image barcodeImage;
            using (barcodeImage = Image.FromFile(@"C:\Users\Administrator\Desktop\YodelShipping\YodelShipping\images\barcode.bmp"))
            {
                using (Graphics g = Graphics.FromImage(barcodeImage))
                {
                    g.DrawString(barcodeText,
                        new Font(barcodeFont, FontStyle.Bold), Brushes.Black, 
                        barcodeImage.Height /2, barcodeImage.Width / 2);
                }
            }
            return barcodeImage;
        }
    }

這是我調用代碼來創建和保存條形碼圖像的地方。 我在調用Save()方法時遇到異常。

System.Drawing.Image img = barcodeHelper.GenerateBarcode("2lgbub51aj+01000002");
img.Save("~/images/barcode.png");

在此輸入圖像描述

protected void Button1_Click(object sender, EventArgs e)
{
    try
    {
        Barcode barcode = new Barcode();
        BarcodeLib.TYPE type = BarcodeLib.TYPE.CODE93;
        BarcodeLib.SaveTypes y = SaveTypes.JPG;
        barcode.Encode(type, "12344");

        barcode.SaveImage(Server.MapPath("~/Barcode\\abc.jpg"), y);
                    Label1.Text = "Image Saved successfully";

    }
    catch (Exception EE)
    {
        EE.ToString();
    }
}

我認為問題在於您的文件路徑(“〜/ images / barcode.png”)。 您需要使用有效的絕對路徑(例如“c:/projects/myproject/images/barcode.png”)。

編輯:我剛才注意到這是ASP.NET,所以你應該只需要這樣做:

img.Save(Server.MapPath("~/images/barcode.png"));

請注意,您可能會在某些時候遇到權限問題(運行ASP.NET應用程序的帳戶將需要此位置的寫入權限)。

  1. 安裝ProcMon(從Microsoft免費)
  2. 運行它並為Path contains barcode.png創建一個過濾器
  3. 運行你的代碼。

它記錄每個文件系統調用和結果(包含詳細信息)

一些想法

  1. 該目錄不存在
  2. 你沒有權限

Image.Save方法需要完整路徑。 代字號(〜)僅適用於ASP.Net。 嘗試:

img.Save(HttpContext.Current.Server.MapPath("~/images/barcode.jpg"));

我認為這與你試圖保存到相對路徑的事實有關。 嘗試使用絕對路徑,或通過調用Environment.CurrentDirectory獲取當前路徑,並將其添加到barcode.png路徑。

我會檢查a)images文件夾存在於你認為它的位置,以及b)你的ASP.NET進程有權寫入它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM