淘宝客结合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>
相关推荐
NetX行者23 分钟前
基于Vue3与ABP vNext 8.0框架实现耗时业务处理的进度条功能
前端·vue.js·进度条·状态模式
顾辰呀1 小时前
WebSocket实战,后台修改订单状态,前台实现数据变更,提供前端和后端多种语言
前端
林奇lc1 小时前
elementUI select,option变化,如果option不存在上次的选项,自动清空上次的选择
前端·vue.js·elementui
杨荧1 小时前
【开源免费】基于Vue和SpringBoot的实习管理系统(附论文)
java·前端·javascript·vue.js·spring boot·spring cloud·java-ee
软件小伟1 小时前
Element UI如何实现按需导入--Vue3篇
前端·javascript·ui·elementui·vue
hccee1 小时前
C# 异常处理、多个异常、自定义异常处理
开发语言·算法·c#
hccee1 小时前
C#中的方法
开发语言·c#
swipe1 小时前
Typescript进阶之类型体操套路四
前端·javascript·typescript
明川2 小时前
Android 性能优化:内存优化(理论篇)
android·前端·性能优化