using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.IO; using System.Linq; using System.Net; using System.Runtime.InteropServices; using System.Windows.Media.Imaging; namespace AllBase { public class ImageBuild { public byte[] Img; public int Width = 0, Height = 0; public Image InitImage = null; public Bitmap InitImagex = null; public string format = ""; public bool CanUser { get { return format == ".jpg" || format == ".png"; } } public ImageBuild(byte[] image) { if (image == null || image.Length == 0) return; Img = image; try { MemoryStream ms = new MemoryStream(Img); InitImage = Image.FromStream(ms); var f = GetImageFormat(InitImage, out format); ms.Close(); Width = InitImage.Width; Height = InitImage.Height; } catch (Exception e) { LogSave.Add(e.Message); } } public byte[] ImageSheild() { if (Width > 700 || Height > 700) { CutToSize(700, 700); } InitImagex = (Bitmap)InitImage; long r = 0, g = 0, b = 0; for (int i = 0; i < InitImagex.Height - 3; i++) { for (int j = 0; j < InitImagex.Width - 3;) { Color c = InitImagex.GetPixel(i, j); int rr = c.R, bb = c.B, gg = c.G; for (int k = 0; k < 3; k++) { for (int l = 0; l < 3; l++) { if (k == 1 && l == 1 || k == 0 && l == 0) continue; var cc = InitImagex.GetPixel(i + k, j + l); if (Math.Abs(cc.R - c.R) > 15 || Math.Abs(cc.B - c.B) > 15 || Math.Abs(cc.G - c.G) > 15) goto End; rr += cc.R; bb += cc.B; gg += cc.G; } } c = Color.FromArgb(rr / 8, gg / 8, bb / 8); InitImagex.SetPixel(i + 1, j + 1, c); End: j++; } } for (int i = 0; i < InitImagex.Height; i++) { for (int j = 0; j < InitImagex.Width; j++) { Color c = InitImagex.GetPixel(i, j); r += c.R; g += c.G; b += c.B; } } int avgR = (int)(r / InitImagex.Height / InitImagex.Width); int avgG = (int)(g / InitImagex.Height / InitImagex.Width); int avgB = (int)(b / InitImagex.Height / InitImagex.Width); int avg = avgB + avgR + avgG; for (int i = 0; i < InitImagex.Height; i++) { for (int j = 0; j < InitImagex.Width; j++) { Color c = InitImagex.GetPixel(i, j); bool add = c.R + c.B + c.G > avg; int rr = add ? c.R < 240 ? c.R + 10 : 255 : c.R > 15 ? c.R - 15 : 0; int gg = add ? c.G < 240 ? c.G + 10 : 255 : c.G > 15 ? c.G - 15 : 0; int bb = add ? c.B < 240 ? c.B + 10 : 255 : c.B > 15 ? c.B - 15 : 0; c = Color.FromArgb(rr, gg, bb); InitImagex.SetPixel(i, j, c); } } InitImagex.Save("1.jpg", ImageFormat.Jpeg); return null; } /// /// 裁剪为指定大小,不符合则返回null /// /// /// /// public byte[] CutToSize(int width, int height) { if (InitImage == null) return null; int w = InitImage.Width; int h = InitImage.Height; if (w < width || h < height) { return null; } int x = 0, y = 0, nw = w, nh = h; int tx = 0, ty = 0, tw = width, th = height; double f = w * 1.0 / width; double t = h * 1.0 / height; if (f == t)//无需变化 { } else if (f > t)//宽度较大 { x = (int)(((f - t) / 2) * width); nw = w - x * 2; } else//高度较大 { y = (int)((t - f) / 2 * height); nh = h - y * 2; } Rectangle fromR = new Rectangle(x, y, nw, nh); Rectangle toR = new Rectangle(tx, ty, tw, th); Bitmap pickedImage = new Bitmap(width, height); Graphics pickedG = Graphics.FromImage(pickedImage); pickedG.InterpolationMode = InterpolationMode.Low; pickedG.SmoothingMode = SmoothingMode.HighSpeed; pickedG.DrawImage(InitImage, toR, fromR, GraphicsUnit.Pixel); //转图片后转二进制数组 InitImage = (Image)pickedImage.Clone(); MemoryStream ms = new MemoryStream(); ImageCodecInfo icc = GetCodeInfo("1.jpg"); long quality = 80; EncoderParameters ep = new EncoderParameters(1); ep.Param[0] = new EncoderParameter(Encoder.Quality, quality); InitImage.Save(ms, icc, ep); byte[] bytes = ms.ToArray(); return bytes; } /// /// 添加线条 /// /// public void AddLineToImage(ref byte[] img) { MemoryStream ms = new MemoryStream(img); var image = (Bitmap)Image.FromStream(ms); ms.Close(); int width = image.Width; int height = image.Height; if (width < 100 || height < 100) return; int r = Randomx.GetId(100, 256); int b = Randomx.GetId(100, 256); int g = Randomx.GetId(100, 256); int h = Randomx.GetId(1, 10); var c = Color.FromArgb(r, g, b); for (int i = 0; i < h; i++) { for (int j = 0; j < height; j++) image.SetPixel(i, j, c); for (int j = 0; j < width; j++) image.SetPixel(j, i, c); } for (int i = height - h; i < height; i++) { for (int j = 0; j < width; j++) image.SetPixel(j, i, c); } for (int i = width - h; i < width; i++) { for (int j = 0; j < height; j++) image.SetPixel(i, j, c); } ImageCodecInfo icc = GetCodeInfo("1.jpg"); long quality = 75; ms = new MemoryStream(); EncoderParameters ep = new EncoderParameters(1); ep.Param[0] = new EncoderParameter(Encoder.Quality, quality); image.Save(ms, icc, ep); img = ms.ToArray(); //FileBase.WriteBytes("1.jpg", bytes); } /// /// 输出固定大小图片,背景白色填充,返回JPG格式二进制代码 /// /// /// /// 最大尺寸KB /// 图片质量 /// public byte[] BuildNewSize(int width, int height, int maxSize, long qu=85l) { if (InitImage == null) return null; int w = InitImage.Width; int h = InitImage.Height; int x = 0, y = 0, nw = w, nh = h; int tx = 0, ty = 0, tw = width, th = height; //先缩放 if (w <= width && h <= height)//无需缩放 { tx = (width - w) / 2; tw = w; ty = (height - h) / 2; th = h; } else if (w < width && h > height) { tx = (width - w) / 2; tw = w; y = (h - height) / 2; nh = height; } else if (w > width && h < height) { ty = (height - h) / 2; th = h; x = (w - width) / 2; nw = width; } else { double f = w * 1.0 / width; double t = h * 1.0 / height; if (f == t)//无需变化 { } else if (f > t)//宽度较大 { x = (int)(((f - t) / 2) * width); nw = w - x * 2; } else//高度较大 { y = (int)((t - f) / 2 * height); nh = h - y * 2; } } Rectangle fromR = new Rectangle(x, y, nw, nh); Rectangle toR = new Rectangle(tx, ty, tw, th); Bitmap pickedImage = new Bitmap(width, height); for (int i = 0; i < pickedImage.Width; i++) { for (int j = 0; j < pickedImage.Height; j++) { Color color = Color.FromArgb(255, 255, 255); pickedImage.SetPixel(i, j, color); } } Graphics pickedG = Graphics.FromImage(pickedImage); pickedG.InterpolationMode = InterpolationMode.Low; pickedG.SmoothingMode = SmoothingMode.HighSpeed; pickedG.DrawImage(InitImage, toR, fromR, GraphicsUnit.Pixel); //转图片后转二进制数组 Image initImagex = (Image)pickedImage.Clone(); MemoryStream ms = new MemoryStream(); ImageCodecInfo icc = GetCodeInfo("1.jpg"); long quality = maxSize == 1024 ? 75l : 85; if (qu > quality) quality = qu; EncoderParameters ep = new EncoderParameters(1); ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality); initImagex.Save(ms, icc, ep); if (ms.Length > maxSize * 1024) { ms = new MemoryStream(); ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 75l); initImagex.Save(ms, icc, ep); return ms.ToArray(); } if (ms.Length > maxSize * 1024) { ms = new MemoryStream(); ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 55l); initImagex.Save(ms, icc, ep); return ms.ToArray(); } if (ms.Length > maxSize * 1024) { return null; } //ImageCodecInfo icc = GetCodeInfo("1.jpg"); //initImagex.Save("22.jpg", icc, ep); return ms.ToArray(); } public byte[] BuildNewSizeCut(int width, int height, int maxSize, long qu = 85l) { if (InitImage == null) return null; int w = InitImage.Width; int h = InitImage.Height; int x = 0, y = 0, nw = w, nh = h; int tx = 0, ty = 0, tw = width, th = height; Rectangle fromR = new Rectangle(x, y, nw, nh); Rectangle toR = new Rectangle(tx, ty, tw, th); Bitmap pickedImage = new Bitmap(width, height); for (int i = 0; i < pickedImage.Width; i++) { for (int j = 0; j < pickedImage.Height; j++) { Color color = Color.FromArgb(255, 255, 255); pickedImage.SetPixel(i, j, color); } } Graphics pickedG = Graphics.FromImage(pickedImage); pickedG.InterpolationMode = InterpolationMode.Low; pickedG.SmoothingMode = SmoothingMode.HighSpeed; pickedG.DrawImage(InitImage, toR, fromR, GraphicsUnit.Pixel); //转图片后转二进制数组 Image initImagex = (Image)pickedImage.Clone(); MemoryStream ms = new MemoryStream(); ImageCodecInfo icc = GetCodeInfo("1.jpg"); long quality = maxSize == 1024 ? 75l : 85; if (qu > quality) quality = qu; EncoderParameters ep = new EncoderParameters(1); ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality); initImagex.Save(ms, icc, ep); if (ms.Length > maxSize * 1024) { ms = new MemoryStream(); ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 75l); initImagex.Save(ms, icc, ep); return ms.ToArray(); } if (ms.Length > maxSize * 1024) { ms = new MemoryStream(); ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 55l); initImagex.Save(ms, icc, ep); return ms.ToArray(); } if (ms.Length > maxSize * 1024) { return null; } //ImageCodecInfo icc = GetCodeInfo("1.jpg"); //initImagex.Save("22.jpg", icc, ep); return ms.ToArray(); } /// /// 根据路径得出图片编码信息 /// /// /// public ImageCodecInfo GetCodeInfo(string path) { string exe = path.Split('.')[path.Split('.').Length - 1].ToLower(); ImageCodecInfo[] icis = ImageCodecInfo.GetImageEncoders(); ImageCodecInfo ici = null, defCodecInfo = null; foreach (ImageCodecInfo i in icis) { if (i.MimeType == "image/jpeg") defCodecInfo = i; if ((exe == "jpg" || exe == "jpeg") && i.MimeType == "image/jpeg") { ici = i; } if (exe == "bmp" && i.MimeType == "image/bmp") { ici = i; } if (exe == "png" && i.MimeType == "image/png") { ici = i; } if (exe == "gif" && i.MimeType == "image/gif") { ici = i; } } if (ici == null) ici = defCodecInfo; return ici; } /// /// 获取Image图片格式 /// /// /// /// private System.Drawing.Imaging.ImageFormat GetImageFormat(Image _img, out string format) { if (_img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Jpeg)) { format = ".jpg"; return System.Drawing.Imaging.ImageFormat.Jpeg; } if (_img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Gif)) { format = ".gif"; return System.Drawing.Imaging.ImageFormat.Gif; } if (_img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Png)) { format = ".png"; return System.Drawing.Imaging.ImageFormat.Png; } if (_img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Bmp)) { format = ".bmp"; return System.Drawing.Imaging.ImageFormat.Bmp; } format = string.Empty; return null; } /// /// 图像缩略图处理 /// /// 图像源数据 /// 压缩质量 1-100 /// 缩略图的宽 /// 缩略图的高 /// public static byte[] ConvertToThumbnail(byte[] bytes, int compression = 100, int thumbWidth = 0, int thumbHeight = 0) { byte[] bs = null; if (bytes != null) { using (MemoryStream ms = new MemoryStream(bytes)) { using (Bitmap srcimg = new Bitmap(ms)) { if (thumbWidth == 0 && thumbHeight == 0) { thumbWidth = srcimg.Width; thumbHeight = srcimg.Height; } using (Bitmap dstimg = new Bitmap(thumbWidth, thumbHeight))//图片压缩质量 { //从Bitmap创建一个System.Drawing.Graphics对象,用来绘制高质量的缩小图。 using (Graphics gr = Graphics.FromImage(dstimg)) { //把原始图像绘制成上面所设置宽高的缩小图 Rectangle rectDestination = new Rectangle(0, 0, thumbWidth, thumbHeight); gr.Clear(Color.White); gr.CompositingQuality = CompositingQuality.HighQuality; gr.SmoothingMode = SmoothingMode.HighQuality; gr.InterpolationMode = InterpolationMode.HighQualityBicubic; gr.DrawImage(srcimg, rectDestination, 0, 0, srcimg.Width, srcimg.Height, GraphicsUnit.Pixel); EncoderParameters ep = new EncoderParameters(1); ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, compression);//设置压缩的比例1-100 ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders(); ImageCodecInfo jpegICIinfo = arrayICI.FirstOrDefault(t => t.FormatID == System.Drawing.Imaging.ImageFormat.Jpeg.Guid); using (MemoryStream dstms = new MemoryStream()) { if (jpegICIinfo != null) { dstimg.Save(dstms, jpegICIinfo, ep); } else { dstimg.Save(dstms, System.Drawing.Imaging.ImageFormat.Jpeg);//保存到内存里 } bs = new Byte[dstms.Length]; dstms.Position = 0; dstms.Read(bs, 0, bs.Length); } } } } } } return bs; } [DllImport("gdi32.dll")] public static extern bool DeleteObject(IntPtr hObject); /// /// 将Image转换为Ico /// /// /// /// public static Icon ConvertToIcon(Image image) { Bitmap bmp = new Bitmap(image); IntPtr h = bmp.GetHicon(); Icon icon = Icon.FromHandle(h); DeleteObject(h); return icon; } List AllList = new List(); List AllColorList = new List(); Dictionary AllPoint = new Dictionary(); public bool ImageCuteNoLogo() { var image = (Bitmap)InitImage; int width = image.Width; int height = image.Height; Color cp1 = image.GetPixel(5, 5); Color cp2 = image.GetPixel(5, width - 5); Color cp3 = image.GetPixel(height - 5, 5); Color cp4 = image.GetPixel(height - 5, width - 5); if (cp1.R < 250 || cp1.B < 250 || cp1.G < 250 || cp2.R < 250 || cp2.B < 250 || cp2.G < 250 || cp3.R < 250 || cp3.B < 250 || cp3.G < 250) { return false; } return true; } public static byte[] BitmapToBytes(Bitmap Bitmap) { MemoryStream ms = null; try { ms = new MemoryStream(); Bitmap.Save(ms, Bitmap.RawFormat); byte[] byteImage = new Byte[ms.Length]; byteImage = ms.ToArray(); return byteImage; } catch (ArgumentNullException ex) { throw ex; } finally { ms.Close(); } } /// /// 字节数组转换为图片 /// /// 字节数组 /// 图片 public static Image BytesToImage(byte[] buffer) { var ms = new MemoryStream(buffer, 0, buffer.Length); Image img = Image.FromStream(ms); ms.Dispose(); return img; } /// /// 图片对象转字节数组 /// /// 图片路径 /// 图片字节数组 private byte[] ImageToBytes(string imagePath) { var fs = new FileStream(imagePath, FileMode.Open); byte[] imgBytes = new byte[fs.Length]; fs.Read(imgBytes, 0, imgBytes.Length); fs.Close(); return imgBytes; } public static Image LoadBitmapLoadBitmipImageFromUrl(string url, out string error) { BitmapImage bi = null; try { bi = LoadBitmipImageFromUrl(url, out error); if (bi == null || !string.IsNullOrEmpty(error)) { error = "获取图片失败 " + error; return null; } } catch (Exception e) { error = "获取图片失败 " + e.Message; return null; } try { return BitmapImageToSystemDrawingImage(bi); } catch (Exception e) { error = "转换图片失败 " + e.Message; return null; } } public static Image BitmapImageToSystemDrawingImage(BitmapImage bitmapImage) { // 方法1 会乱码花屏 //int width = bitmapImage.PixelWidth; //int height = bitmapImage.PixelHeight; //int stride = width * ((bitmapImage.Format.BitsPerPixel + 7) / 8); //byte[] pixels = new byte[stride * height]; //bitmapImage.CopyPixels(pixels, stride, 0); //Bitmap bitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb); //BitmapData bmpData = bitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, bitmap.PixelFormat); //Marshal.Copy(pixels, 0, bmpData.Scan0, pixels.Length); //bitmap.UnlockBits(bmpData); //return bitmap; // 方法2 using (MemoryStream stream = new MemoryStream()) { BitmapEncoder encoder = new BmpBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(bitmapImage)); encoder.Save(stream); stream.Position = 0; Bitmap bitmap = new Bitmap(stream); stream.Close(); //// 现在你可以将这个Bitmap对象用于Windows Forms的PictureBox或其他图像显示控件 //PictureBox pictureBox = new PictureBox(); //pictureBox.Image = bitmap; // 或者如果你已经有了一个PictureBox控件,直接设置其Image属性 return bitmap; } } public static BitmapImage LoadBitmipImageFromUrl(string url, out string error) { BitmapImage bitmap = new BitmapImage(); error = ""; try { using (WebClient webClient = new WebClient()) { // 下载图片数据到内存流 using (MemoryStream stream = new MemoryStream(webClient.DownloadData(url))) { stream.Position = 0; // 重置流的位置到开始处 bitmap.BeginInit(); bitmap.CreateOptions = BitmapCreateOptions.PreservePixelFormat; bitmap.CacheOption = BitmapCacheOption.OnLoad; // 或者使用 BitmapCacheOption.OnLoad 以减少内存使用 bitmap.UriSource = null; // 清除可能的旧UriSource,防止缓存问题 bitmap.StreamSource = stream; bitmap.EndInit(); bitmap.Freeze(); // 防止后续更改,提高性能 } } } catch (Exception ex) { // 处理异常,例如打印错误信息或设置一个默认图片等 //Console.WriteLine("Error loading image: " + ex.Message); error = ex.Message; return null; } return bitmap; } } public class ImagePiex { public Point point { get; set; } public Color color { get; set; } public bool Pval = false; public bool Used = false; public int imgCount = 0; } }