采集base64图片

2018-07-30 12:00:00
137
摘要:base64格式的图片直接下载到磁盘

在内容过滤中运行C#代码

注:路径“ D:\\download\\”可以修改,但是需要提前创建好文件夹。

using System;
using System.Collections.Generic;
using SpiderInterface;
class LocoyCode{
    /// <summary>
    /// 执行方法,不能修改类和方法名称。
    /// </summary>
    /// <param name="content">标签内容</param>
    /// <param name="response">页面响应,包含了Url、原始Html等属性</param>
    /// <returns>返回处理后的标签内容</returns>
    public string Run(string content,ResponseEntry response){        
            int start = content.IndexOf("/");
            int end = content.IndexOf(";");
            string ext = content.Substring(start + 1, end - start - 1);
            System.Drawing.Imaging.ImageFormat format = System.Drawing.Imaging.ImageFormat.Png;

            switch (ext.ToLower())
            {
                case "bmp":
                    format = System.Drawing.Imaging.ImageFormat.Bmp;
                    break;
                case "emf":
                    format = System.Drawing.Imaging.ImageFormat.Emf;
                    break;
                case "wmf":
                    format = System.Drawing.Imaging.ImageFormat.Wmf;
                    break;
                case "gif":
                    format = System.Drawing.Imaging.ImageFormat.Gif;
                    break;
                case "jpg":
                    format = System.Drawing.Imaging.ImageFormat.Jpeg;
                    break;
                case "png":
                    format = System.Drawing.Imaging.ImageFormat.Png;
                    break;
                case "tiff":
                    format = System.Drawing.Imaging.ImageFormat.Tiff;
                    break;
                case "exif":
                    format = System.Drawing.Imaging.ImageFormat.Exif;
                    break;
                case "icon":
                    format = System.Drawing.Imaging.ImageFormat.Icon;
                    break;
            }
            String filename =Guid.NewGuid().ToString() + "."+ext;
            String path="D:\\download\\" + filename;

            String base64 = content.Substring(content.IndexOf(",") + 1); 

            System.Drawing.Bitmap bitmap = null;

            try
            {
                String inputStr = base64;

                byte[] arr = Convert.FromBase64String(inputStr);

                using (System.IO.MemoryStream ms = new System.IO.MemoryStream(arr))
                {
                    using (System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(ms))
                    {
                        ms.Close();
                        bitmap = bmp;
                        bitmap.Save(path, System.Drawing.Imaging.ImageFormat.Gif);
                    }
                }
            }
            catch (Exception)
            {
            }
            return filename;
    }
}


发表评论
评论通过审核后显示。