C#将图像数据写入PNG文件

环境: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 厦门

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值