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

阿里云存储图像bug修复

整张图像可以正常获取,获取部分区域时,提示图像损坏。 

public partial class test : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //{ X = 1014 Y = 581 Width = 918 Height = 242}

        //string paperPic0 = aliyun.GetSignedUrl("b88895bd9db14c6196895cf55d28206d99.png");                                                     // 整图,可正常访问
        string paperPic = aliyun.GetSignedUrl("b88895bd9db14c6196895cf55d28206d99.png", new System.Drawing.Rectangle(1014, 581, 918, 242));     // 整图上的部分区域,无法访问。

        //Response.Write(paperPic);
        Response.Redirect(paperPic);
    }
}

0040-00000002


修复方案:下载整图到本地,根据需要自行裁切。

1、检测阿里云图像url,是否为有效的图像
/// <summary>
/// 获取url响应类型信息
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
private static string getResponseType(string url)
{
    try
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        var response = request.GetResponse();
        if (response.ContentLength > 0)
        {
            string type = response.ContentType;
            if (type.Length > 0) type = type.ToLower();

            return type;      // image/png
        }
    }
    catch (Exception ex)
    {
        return ex.ToString();
    }
    return "";
}
2、检测到非有效图像,则获取整图,后自行裁切

将所有aliyun.GetSignedUrl()接口调用,指向函数GetCloudUrl()。


/// <summary>
/// 获取图像地址后,先检测是否是有效的图像地址。
/// 是有效图像,则返回;
/// 否则获取整图,后根据rect裁切生成。
/// </summary>
/// <param name="file"></param>
/// <param name="r"></param>
/// <returns></returns>
private static string GetCloudUrl(string file, Rectangle r)
{
    try
    {
        if (r != Rectangle.Empty)
        {
            string url = aliyun.GetSignedUrl(file, r);
            string responseType = getResponseType(url);
            if (responseType.Length > 0 && responseType.StartsWith("image/"))
            {
                return url;
            }
            else
            {
                url = aliyun.GetSignedUrl(file, Rectangle.Empty);
                responseType = getResponseType(url);
                if (responseType.Length > 0 && responseType.StartsWith("image/"))
                {
                    //url = "/pages/Img?src=" + HttpUtility.UrlEncode(url) + "&rect=" + HttpUtility.UrlEncode(r.X + "_" + r.Y + "_" + r.Width + "_" + r.Height);
                    //return url;

                    return getWebImgBlockUrl(url, r.X, r.Y, r.Width, r.Height);
                }
            }
        }
        else
        {
            string url = aliyun.GetSignedUrl(file, Rectangle.Empty);
            string responseType = getResponseType(url);
            if (responseType.Length > 0 && responseType.StartsWith("image/"))
            {
                return url;
            }
        }
    }
    catch(Exception ex) 
    { 
        Aspxnet.Web.DLog.Write(ex.ToString()); 
    }

    string rectStr = "";
    if (r != Rectangle.Empty)
    {
        rectStr = (" ,rect:" + r.X + "_" + r.Y + "_" + r.Width + "_" + r.Height);
    }
    return "图像获取失败!" + file + rectStr;

}

/// <summary>
/// 获取url地址对应的图像
/// </summary>
/// <returns></returns>
public static string getWebImgBlockUrl(string url, int x, int y, int width, int height)
{
    var host = System.Configuration.ConfigurationManager.AppSettings["HostName"];
    if (host.EndsWith("/")) host = host.Substring(0, host.Length - 1);
    return host + "/pages/Img?src=" + HttpUtility.UrlEncode(url) + "&rect=" + HttpUtility.UrlEncode(x + "_" + y + "_" + width + "_" + height);
}
Img.cshtml (实现网址图像的下载与自定义区域裁切)
@using System.Drawing;
@using System.Web;
@{
    var src = Request["src"];
    Response.Clear();
    try
    {
        Bitmap img = GetWebPic(src);
        OutPutPic(img, DateTime.Now.Ticks + "", Response);
    }
    catch { }
    Response.Write("");
}

@functions  {

    /// <summary>
    /// 输出图像
    /// </summary>
    /// <param name="pic"></param>
    /// <param name="filename"></param>
    /// <param name="Response"></param>
    private void OutPutPic(Bitmap pic, string filename, HttpResponseBase Response)
    {
        if (pic == null) return;
        System.IO.MemoryStream stream = new System.IO.MemoryStream();
        pic.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
        Response.ClearContent();
        Response.ContentType = "Image/png";
        if (!filename.EndsWith(".png")) filename += ".png";
        Response.AddHeader("Content-Disposition", "filename=" + HttpUtility.UrlEncode(filename, System.Text.Encoding.UTF8));
        Response.BinaryWrite(stream.ToArray());
    }


    /// <summary>
    /// 获取url地址对应的图像
    /// </summary>
    /// <param name="url"></param>
    /// <returns></returns>
    private Bitmap GetWebPic(string url)
    {
        try
        {
            WebClient client = new WebClient();
            byte[] data = client.DownloadData(url);
            System.IO.MemoryStream stream = new System.IO.MemoryStream();
            stream.Write(data, 0, data.Length);
            Bitmap pic = (Bitmap)Bitmap.FromStream(stream);
            pic = GetRect(pic);
            return pic;
        }
        catch (Exception ex)
        {
            return null;
        }
    }

    private Bitmap GetRect(Bitmap pic)
    {
        try
        {
            if (Request["rect"] != null)
            {
                string rect = Request["rect"] + "";
                int[] Rec = rect.Trim().Split('_').Select(x => Convert.ToInt32(x.Trim())).ToArray();
                return GetRect(pic, new Rectangle(Rec[0], Rec[1], Rec[2], Rec[3]));
            }
        }
        catch{}
        return pic;
    }

    private Bitmap GetRect(Bitmap pic, Rectangle rect)
    {
        var tmp = new Bitmap(rect.Width, rect.Height);
        Graphics g = Graphics.FromImage(tmp);
        g.DrawImage(pic, new Rectangle(0, 0, tmp.Width, tmp.Height), rect, GraphicsUnit.Pixel);
        g.Dispose();
        return tmp;
    }

}

修复后


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

相关文章:

  • 【Rust自学】12.3. 重构 Pt.1:改善模块化
  • mermaid大全(语法、流程图、时序图、甘特图、饼图、用户旅行图、类图)
  • 使用Docker模拟PX4固件的无人机用于辅助地面站开发
  • mysql的mvcc理解
  • winform监听全局鼠标事件
  • 单片机(MCU)-简单认识
  • 4. scala高阶之隐式转换与泛型
  • vue3+vite+ts集成第三方js
  • 【文件锁】多进程线程安全访问文件demo
  • 【初识扫盲】逆概率加权
  • Windows 10 ARM工控主板连接I2S音频芯片
  • 32_Redis分片集群原理
  • 《零基础Go语言算法实战》【题目 2-26】goroutine 的执行效率问题
  • HDFS 的API的操作
  • 【Rust】函数
  • 【网络协议】EIGRP - 第二部分
  • 使用Deepseek搭建类Cursor编辑器
  • SQL语言的计算机基础
  • LeetCode:216.组合总和III
  • 基于单片机的书写坐姿规范提醒器的设计(论文+源码)
  • 自动化机械臂视觉跟踪和手眼校准
  • Docker Swarm、Kubernetes 和 LVS 的功能对比
  • Go语言如何实现高性能缓存服务
  • 青少年编程与数学 02-006 前端开发框架VUE 24课题、UI表单
  • virtual box虚拟机误删Python3.6后导致UBUNTU18.04开机无UI界面(进不了desktop)的解决方法
  • docker推送本地仓库报错