环境:Windows 10 x64, VS2017
问题:使用C#语言将图像数据写入到PNG格式的图片文件中
代码:
// Mylaf
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Drawing;
using System.Drawing.Imaging;
namespace CS_ConsoleTest
{
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct StPoint
{
public Int64 X, Y;
public StPoint(Int64 _x, Int64 _y) { X = _x; Y = _y; }
}
public class ImageWarp
{
// using System.Drawing;
// using System.Drawing.Imaging;
public Bitmap bmp;
public Graphics gph;
public ImageWarp(Int32 width, Int32 height)
{
bmp = new Bitmap(width, height);
gph = Graphics.FromImage(bmp);
//
gph.Clear(Color.Empty);
}
public void DrawPoint(StPoint pt, Color color, Single thickness = 1.0f)
{
gph.DrawEllipse(new Pen(color, thickness), (int)pt.X - thickness * 0.5f, (int)pt.Y - thickness * 0.5f, thickness, thickness);
//gph.FillEllipse();
}
public void DrawLine(StPoint p0, StPoint p1, Color color, Single thickness = 1.0f)
{
gph.DrawLine(new Pen(color, thickness), p0.X, p0.Y, p1.X, p1.Y);
}
public void DrawPolygon(StPoint[] points, Color color, Single thickness = 1.0f)
{
gph.DrawPolygon(new Pen(color, thickness), DataWarp.ToWinPoints(points));
}
public void Save(string filename)
{
gph.Save();
gph.Dispose();
bmp.MakeTransparent(Color.Transparent);
bmp.Save(filename, ImageFormat.Png);
}
public static void Demo01()
{
ImageWarp image = new ImageWarp(512, 512);
image.DrawLine(new StPoint(256, 0), new StPoint(256, 511), Color.Blue, 1.0f);
image.DrawLine(new StPoint(0, 256), new StPoint(511, 256), Color.Red, 1.0f);
image.DrawPoint(new StPoint(256, 256), Color.Green, 2.0f);
image.DrawPoint(new StPoint(0, 0), Color.Black, 10.0f);
image.Save("ImageWarp.Demo01.png");
}
}
}
main函数:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CS_ConsoleTest
{
class Program
{
static void Main(string[] args)
{
ImageWarp.Demo01();
}
}
}
结果:
// Mylaf
// 2019-11-08 厦门