当前位置: 首页 > article >正文

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

需要注意的点:

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

1、后台API

        /// <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

.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、页面

<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

 <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>


http://www.kler.cn/a/400249.html

相关文章:

  • 3. langgraph中的react agent使用 (在react agent添加系统提示)
  • oracle19c开机自启动
  • 学习threejs,使用AnimationMixer实现变形动画
  • 2024年11月16日 星期六 重新整理Go技术
  • Py之pymupdf:基于langchain框架结合pymupdf库实现输出每个PDF页面的文本内容、元数据等
  • C++11(四)---可变参数模板
  • 界面控件DevExpress WinForms v24.2新功能预览 - 支持.NET 9
  • 社交电商的优势及其与 AI 智能名片小程序、S2B2C 商城系统的融合发展
  • Java篇String类的常见方法
  • 基于YOLOv8深度学习的智慧交通非机动车驾驶员头盔佩戴检测系统
  • Matlab实现白鲸优化算法优化随机森林算法模型 (BWO-RF)(附源码)
  • 在Keil中使用ST-LINK烧录STM32程序指南
  • 聚焦 AUTO TECH 2025华南展:探索新能源汽车发展新趋势
  • 美赛优秀论文阅读--2023C题
  • Spring Boot汽车资讯:数字化时代的驾驶
  • 前端性能优化深入解析:提升用户体验的几个关键点
  • 工具类-基于 axios 的 http 请求工具 Request
  • ELK8.15.4搭建开启安全认证
  • 基于Vue3与ABP vNext 8.0框架实现耗时业务处理的进度条功能
  • 常见网络厂商设备默认用户名/密码大全
  • 移动端web页面调用原生jsbridge的封装
  • java ssm 高速公路管理系统 公路收费管理 高速收费管理 源码 jsp
  • 【Android】Proxyman 抓 HTTP 数据包
  • 4 设计模式原则之接口隔离原则
  • 【开源风云】从若依系列脚手架汲取编程之道(七)
  • 【青牛科技】D7312带 ALC 双通道前置放大器电路