Files
29WxOrder/AllBase/ImageBuild.cs
T
2026-10-19 15:13:18 +08:00

534 lines
19 KiB
C#

using CefSharp.DevTools.IO;
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Media.Imaging;
namespace AllBase
{
public class ImageBuild
{
public byte[] Img;
public int Width = 0, Height = 0;
public Image InitImage = null;
public ImageBuild(byte[] image)
{
if (image == null || image.Length == 0)
return;
Img = image;
try
{
MemoryStream ms = new MemoryStream(Img);
InitImage = Image.FromStream(ms);
ms.Close();
}
catch (Exception e)
{
LogSave.Add(e.Message);
}
Width = InitImage.Width;
Height = InitImage.Height;
}
/// <summary>
/// 裁剪为指定大小,不符合则返回null
/// </summary>
/// <param name="width"></param>
/// <param name="height"></param>
/// <returns></returns>
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;
width = w;
height = h;
}
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);
//转图片后转二进制数组
Image initImagex = (Image)pickedImage.Clone();
MemoryStream ms = new MemoryStream();
ImageCodecInfo icc = GetCodeInfo("1.jpg");
long quality = 75;
EncoderParameters ep = new EncoderParameters(1);
ep.Param[0] = new EncoderParameter(Encoder.Quality, quality);
initImagex.Save(ms, icc, ep);
byte[] bytes = ms.GetBuffer();
return bytes;
}
/// <summary>
/// 添加线条
/// </summary>
/// <param name="img"></param>
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);
}
/// <summary>
/// 输出固定大小图片,背景白色填充,返回JPG格式二进制代码
/// </summary>
/// <param name="width"></param>
/// <param name="height"></param>
/// <param name="maxSize">最大尺寸KB</param>
/// <returns></returns>
public byte[] BuildNewSize(int width, int height, int maxSize)
{
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 = 75;
EncoderParameters ep = new EncoderParameters(1);
ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
initImagex.Save(ms, icc, ep);
byte[] bytes = ms.GetBuffer();
if (bytes.Length > maxSize * 1024)
{
ms = new MemoryStream();
ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 65l);
initImagex.Save(ms, icc, ep);
bytes = ms.GetBuffer();
}
if (bytes.Length > maxSize * 1024)
{
ms = new MemoryStream();
ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 55l);
initImagex.Save(ms, icc, ep);
bytes = ms.GetBuffer();
}
if (bytes.Length > maxSize * 1024)
{
return null;
}
//ImageCodecInfo icc = GetCodeInfo("1.jpg");
//initImagex.Save("22.jpg", icc, ep);
return bytes;
}
/// <summary>
/// 根据路劲得出图片编码信息
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
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;
}
/// <summary>
/// image 大小转换
/// </summary>
/// <param name="imgToResize"></param>
/// <param name="size"></param>
/// <returns></returns>
public static System.Drawing.Image resizeImage(System.Drawing.Image imgToResize, Size size)
{
//获取图片宽度
int sourceWidth = imgToResize.Width;
//获取图片高度
int sourceHeight = imgToResize.Height;
float nPercent = 0;
float nPercentW = 0;
float nPercentH = 0;
//计算宽度的缩放比例
nPercentW = ((float)size.Width / (float)sourceWidth);
//计算高度的缩放比例
nPercentH = ((float)size.Height / (float)sourceHeight);
if (nPercentH < nPercentW)
nPercent = nPercentH;
else
nPercent = nPercentW;
//期望的宽度
int destWidth = (int)(sourceWidth * nPercent);
//期望的高度
int destHeight = (int)(sourceHeight * nPercent);
Bitmap b = new Bitmap(destWidth, destHeight);
Graphics g = Graphics.FromImage((System.Drawing.Image)b);
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
//绘制图像
g.DrawImage(imgToResize, 0, 0, destWidth, destHeight);
g.Dispose();
return (System.Drawing.Image)b;
}
[DllImport("gdi32.dll")]
public static extern bool DeleteObject(IntPtr hObject);
/// <summary>
/// 将Image转换为Ico
/// </summary>
/// <param name="image"></param>
/// <param name="nullTonull"></param>
/// <returns></returns>
public static Icon ConvertToIcon(Image image)
{
Bitmap bmp = new Bitmap(image);
IntPtr h = bmp.GetHicon();
Icon icon = Icon.FromHandle(h);
DeleteObject(h);
return icon;
}
public static Icon ConvertToIcon(Bitmap bmp)
{
IntPtr h = bmp.GetHicon();
Icon icon = Icon.FromHandle(h);
DeleteObject(h);
return icon;
}
public static Image LoadBitmapLoadBitmipImageFromUrl(string url)
{
try
{
BitmapImage bi = LoadBitmipImageFromUrl(url);
return BitmapImageToSystemDrawingImage(bi);
}
catch (Exception e)
{
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, int? width = null, int? height = null)
{
BitmapImage bitmap = new BitmapImage();
try
{
using (WebClient webClient = new WebClient())
{
// 下载图片数据到内存流
using (MemoryStream stream = new MemoryStream(webClient.DownloadData(url)))
{
stream.Position = 0; // 重置流的位置到开始处
bitmap.BeginInit();
if (width != null && height != null)
{
bitmap.DecodePixelWidth = width.Value;
bitmap.DecodePixelHeight = height.Value;
}
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);
return null;
}
return bitmap;
}
public static async Task<BitmapImage> LoadBitmipImageFromUrlAsync(string url, int? width = null, int? height = null)
{
BitmapImage bitmap = new BitmapImage();
try
{
//using (WebClient webClient = new WebClient())
//{
//webClient.DownloadDataCompleted += (sender, e) =>
//{
// if (e.Cancelled)
// {
// //Console.WriteLine("下载已取消");
// bitmap = null;
// }
// else if (e.Error != null)
// {
// //Console.WriteLine("下载出错: " + e.Error.Message);
// bitmap = null;
// }
// else
// {
// byte[] data = (byte[])e.Result;
// //string text = System.Text.Encoding.UTF8.GetString(data);
// //Console.WriteLine(text);
// // 下载图片数据到内存流
// using (MemoryStream stream = new MemoryStream(data))
// {
// stream.Position = 0; // 重置流的位置到开始处
// bitmap.BeginInit();
// if (width != null && height != null)
// {
// bitmap.DecodePixelWidth = width.Value;
// bitmap.DecodePixelHeight = height.Value;
// }
// bitmap.CreateOptions = BitmapCreateOptions.PreservePixelFormat;
// bitmap.CacheOption = BitmapCacheOption.OnLoad; // 或者使用 BitmapCacheOption.OnLoad 以减少内存使用
// bitmap.UriSource = null; // 清除可能的旧UriSource,防止缓存问题
// bitmap.StreamSource = stream;
// bitmap.EndInit();
// bitmap.Freeze(); // 防止后续更改,提高性能
// }
// }
//};
//await webClient.DownloadDataAsync(new Uri(url));
//}
using (HttpClient client = new HttpClient())
{
// 下载图片数据到内存流
using (MemoryStream stream = new MemoryStream(await client.GetByteArrayAsync(url)))
{
stream.Position = 0; // 重置流的位置到开始处
bitmap.BeginInit();
if (width != null && height != null)
{
bitmap.DecodePixelWidth = width.Value;
//bitmap.DecodePixelHeight = height.Value;
}
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);
return null;
}
return bitmap;
}
//public string BitmapImageToBase64(BitmapImage bitmapImage)
//{
// // 创建一个 RenderTargetBitmap 对象来渲染 BitmapImage
// RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap(
// (int)bitmapImage.PixelWidth,
// (int)bitmapImage.PixelHeight,
// bitmapImage.DpiX,
// bitmapImage.DpiY,
// System.Windows.Media.PixelFormats.Pbgra32);
// renderTargetBitmap.Render(bitmapImage);
// // 将 RenderTargetBitmap 保存到内存流中
// PngBitmapEncoder encoder = new PngBitmapEncoder();
// encoder.Frames.Add(BitmapFrame.Create(renderTargetBitmap));
// using (MemoryStream memoryStream = new MemoryStream())
// {
// encoder.Save(memoryStream);
// byte[] imageBytes = memoryStream.ToArray();
// string base64String = Convert.ToBase64String(imageBytes);
// return base64String;
// }
//}
}
}