淘宝客结合C#使用WebApi和css绘制商品图片

需要注意的点:

绘制出来的图上传至服务器导致服务器内存溢出,所以要把图片文件转换为字节流文件输出

1、后台API

cs 复制代码
        /// <summary>
        /// 淘宝客商品分享
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("tbkgoodsshare")]
        [TenantSite]
        public async Task<IHttpActionResult> TbkGoodsShareImage(string source, string picUrl, string title, string marketPrice, string buyPrice, string couponAmount, string buyUrl, string couponClickUrl)
        {
            ResultJsonModel respond = new ResultJsonModel();
            Dictionary<string, object> data = new Dictionary<string, object>();
            respond.data = data;

            //模板图片
            string imgmb = "http://cdn地址/imgs/hpxx/tbk_goods_fx.jpg";

            //用户信息
            TenantSiteModel tenantSite = ActionContext.ActionArguments[ApiConsts.CurrentTenantSite] as TenantSiteModel;
            string u_key = ActionContext.ActionArguments[ApiConsts.UserLoginKey] as string;
            var udata = await _userSessionCacheManager.GetCurentUsersFromCache(u_key);
            #region 合成图片
             //模板图
            Stream stream = ImageHelper.help.GetRemoteImage(imgmb);
            if (stream == null)
            {
                respond.msg = "模板图片不存在";
                return Ok(respond);
            }
            //产品主图
            Stream streampic = ImageHelper.help.GetRemoteImage(picUrl);
            if (streampic == null)
            {
                respond.msg = "产品图片不存在";
                return Ok(respond);
            }
            Image origina = Image.FromStream(stream);
            Image pimg = Image.FromStream(streampic);
            stream.Close();
            streampic.Close();

            Graphics g = Graphics.FromImage(origina);
            //绘制产品主图
            g.DrawImage(pimg, 35, 150, 560, 560);
            //绘制二维码
            var qcodeurl = string.Empty;
            if (string.IsNullOrEmpty(couponClickUrl))
                qcodeurl = buyUrl;
            else
                qcodeurl = couponClickUrl;
            Bitmap bmp = QRcodeHelper.CreateQRcode(qcodeurl, 11);
            g.DrawImage(bmp, 448, 770, 153, 153);

            //绘制产品标题
            var goodsname = title.Length > 36 ? title.Substring(0, 36) : title;
            TextFormatFlags flags = TextFormatFlags.WordBreak;
            Rectangle rect = new Rectangle(22, 769, 400, 108);
            TextRenderer.DrawText(g, goodsname, new Font("微软雅黑", 20, FontStyle.Regular, GraphicsUnit.Pixel), rect, Color.FromArgb(56, 56, 56), flags);
            //绘制来源
            Pen pen = new Pen(Color.FromArgb(240, 37, 154), 2);
            RectangleF drawRect = new RectangleF(28, 890, 35, 20);
            g.DrawRectangle(pen, 22, 885, 46, 27);
            // Set format of string.
            StringFormat drawFormat = new StringFormat();
            drawFormat.Alignment = StringAlignment.Center;
            // Draw string to screen.
            g.DrawString(source, new Font("微软雅黑", 13, FontStyle.Bold, GraphicsUnit.Pixel), new SolidBrush(Color.FromArgb(240, 37, 154)), drawRect, drawFormat);
            //绘制会员名
            g.DrawString("来自[" + udata.nick_name + "]的贴心推荐", new Font("微软雅黑", 15, FontStyle.Regular, GraphicsUnit.Pixel), new SolidBrush(Color.FromArgb(147, 147, 147)), new Rectangle(190, 117, 260, 36));
            //绘制价格
            g.DrawString("¥ ", new Font("微软雅黑", 25, FontStyle.Regular, GraphicsUnit.Pixel), new SolidBrush(Color.FromArgb(240, 37, 154)), new Rectangle(100, 918, 35, 30));
            g.DrawString(string.Format("{0:F}", Convert.ToDecimal(buyPrice) / 100), new Font("微软雅黑", 35, FontStyle.Regular, GraphicsUnit.Pixel), new SolidBrush(Color.FromArgb(240, 37, 154)), new Rectangle(120, 908, 90, 40));
            //绘制市场价
            g.DrawString("原价:¥" + string.Format("{0:F}", Convert.ToDecimal(marketPrice) / 100), new Font("微软雅黑", 20, FontStyle.Strikeout, GraphicsUnit.Pixel), new SolidBrush(Color.FromArgb(154, 154, 154)), new Rectangle(220, 918, 200, 40));
            //绘制优惠券
            g.DrawString(string.Format("{0:F}", couponAmount) + "元券", new Font("微软雅黑", 18, FontStyle.Regular, GraphicsUnit.Pixel), new SolidBrush(Color.FromArgb(255, 255, 255)), new Rectangle(53, 965, 70, 25));
            MemoryStream ms = new MemoryStream();
            origina.Save(ms, ImageFormat.Jpeg);
  g.Dispose();
            origina.Dispose();
            pimg.Dispose();
            #endregion

            byte[] imgbt = ms.GetBuffer();
            string base64Str = Convert.ToBase64String(imgbt);

            data.Add(ResultData.data_key.ToString(), base64Str);
            respond.code = ResultCode.Correct;
            respond.msg = "success";
            return Ok(respond);
        }

2、前台页面css

css 复制代码
.pop_bg {
    position: fixed;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0,0,0,0.5);
    z-index: 100;
}

    .pop_bg .pop_img {
        position: absolute;
        left: 15%;
        right: 15%;
        top: 15%;
        border-radius: 10px;
        overflow: hidden;
    }
 .pop_bg .pop_img img {
            width: 100%;
        }

        .pop_bg .pop_img i {
            position: absolute;
            right: 4px;
            top: 4px;
            background: url(../imgs/hpxx/close.png) no-repeat center center;
            background-size: 22px 22px;
            width: 30px;
            height: 30px;
        }

.free_ad {  width: 100%;
    position: absolute;
    left: 0;
    bottom: 10px;
    color: #393b91;
    font-size: 14px;
    text-align: center;
}

3、页面

html 复制代码
<div class="pop_bg" style="display:none;">
    <div class="pop_img">
        <img class="fxewm" src=""><i class="close"></i>
        <p class="free_ad">长按保存图片</p>
    </div>
</div>

4、js

javascript 复制代码
 <script type="text/javascript">
        $(function () {
            $.ajax({
                type: 'get',
                url: $f.apihost + 'uinfo/tbkgoodsshare',
                data: {
                    "source": "天猫",
                    "picUrl": "https://cdn地址/i4/2452755802/O1CN01M4XigM1sjMZSkkKnz_!!0-item_pic.jpg",
                    "title": "可水洗家务清洁懒人抹布厨房无纺布巾干湿两用家用纸一次性洗碗布10.5",
                    "marketPrice": "48",
                    "buyPrice": "16.10",
                    "buyUrl": "//s.click.taobao.com/t?e=m=2&s=KK/DZMDacwBw4vFB6t2Z2ueEDrYVVa64Dne87AjQPk9yINtkUhsv0IArzX8noqdbhTHH3SLdpkDa7xIGlJ/ezzgsLdZJzm/P5n09zUy+/CDQixZmXtrdQDZvalXXivAGUyNpxLfgKr0jWpzpm6nEC1Y7oKTxnsCvgFxgvEFCbV34JvEYI/fYOLw/+331Bhx4osKHgik4TatPhItcl68Yp8Yl7w3/A2kb&union_lens=lensId:MAPI@1587813481@0b58a109_0e94_171b10efde4_2eeb@01",
                    "couponAmount": "3",
                    "couponClickUrl":  "www.baidu.com",
                },
                success: function (data) {
                    if (data.code == 1) {
                        $(".fxewm").attr("src", "data:image/jpeg;base64," + data.data.data_key);
                        $(".pop_bg").show();
                    }
                },
                complete: function () {  
                    $.hideLoading();
                }
            });
        });
    </script>
相关推荐
前端小小王21 分钟前
React Hooks
前端·javascript·react.js
迷途小码农零零发31 分钟前
react中使用ResizeObserver来观察元素的size变化
前端·javascript·react.js
娃哈哈哈哈呀1 小时前
vue中的css深度选择器v-deep 配合!important
前端·css·vue.js
Java Fans1 小时前
C# 中串口读取问题及解决方案
开发语言·c#
盛派网络小助手1 小时前
微信 SDK 更新 Sample,NCF 文档和模板更新,更多更新日志,欢迎解锁
开发语言·人工智能·后端·架构·c#
码农君莫笑1 小时前
信管通低代码信息管理系统应用平台
linux·数据库·windows·低代码·c#·.net·visual studio
旭东怪1 小时前
EasyPoi 使用$fe:模板语法生成Word动态行
java·前端·word
鲤籽鲲2 小时前
C# Random 随机数 全面解析
android·java·c#
ekskef_sef3 小时前
32岁前端干了8年,是继续做前端开发,还是转其它工作
前端