You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET C#生成二维码尺寸不符求助:指定150x150却生成1060x1060

解决二维码生成尺寸与设定不符的问题

你当前的代码里,虽然设置了imgBarCode的宽高为150x150,但这个控件的尺寸只是用于前端显示,实际保存到文件的是qrCode.GetGraphic(20)生成的原始Bitmap——这个Bitmap的尺寸由二维码的模块数量、每个模块的像素大小(你传的20)以及默认边距计算而来,所以会生成1060x1060的图片。

要生成150x150的二维码文件,需要在生成Bitmap后将其缩放到目标尺寸,再保存。修改后的代码如下:

protected string set_QrCode(string fileLink)
{
    string code = fileLink;
    QRCodeGenerator qrGenerator = new QRCodeGenerator();
    QRCodeGenerator.QRCode qrCode = qrGenerator.CreateQrCode(code, QRCodeGenerator.ECCLevel.Q);
    
    // 生成原始二维码Bitmap
    using (Bitmap originalBitMap = qrCode.GetGraphic(20))
    {
        // 将原始Bitmap缩放到150x150
        using (Bitmap scaledBitMap = new Bitmap(originalBitMap, new Size(150, 150)))
        {
            using (MemoryStream ms = new MemoryStream())
            {
                scaledBitMap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                byte[] byteImage = ms.ToArray();
                
                // 生成文件名并保存文件
                var filename = $"{Guid.NewGuid().ToString().Substring(0,5)}{Guid.NewGuid().ToString().Substring(0,5)}{DateTime.Now.ToString("FFFFFF")}{DateTime.Now.Minute}.png";
                var filePath = HttpContext.Current.Server.MapPath($"~/docs/certificates/{filename}");
                System.IO.File.WriteAllBytes(filePath, byteImage);

                return $"~/docs/certificates/{filename}";
            }
        }
    }
}

关键改动说明

  • 新增了scaledBitMap,通过new Bitmap(originalBitMap, new Size(150, 150))将原始大尺寸二维码缩放到目标尺寸
  • 保存的是缩放后的scaledBitMap,而非原始Bitmap
  • 移除了无用的FileUpload和Image控件代码(你最终是生成文件返回路径,这两个控件对你的场景没有作用)

内容的提问来源于stack exchange,提问作者NetProjects Ir

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 13:24:21