好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

C#本地图片转二进制数据完整示例代码


using System;

using System.Drawing;

using System.IO;

using System.Windows.Forms;

public partial class MainForm : Form

{

    private PictureBox pictureBox1;

    public MainForm()

    {

        InitializeComponent();

        // 初始化控件

        pictureBox1 = new PictureBox

        {

            SizeMode = PictureBoxSizeMode.Zoom,

            Dock = DockStyle.Fill

        };

        this.Controls.Add(pictureBox1);

        // 示例:从文件读取二进制数据并显示

        byte[] imageBytes = File.ReadAllBytes("test.jpg");

        DisplayImage(imageBytes);

    }

    public void DisplayImage(byte[] imageBytes)

    {

        try

        {

            using (MemoryStream ms = new MemoryStream(imageBytes))

            {

                // 释放之前的图片资源(避免内存泄漏)

                if (pictureBox1.Image != null)

                {

                    pictureBox1.Image.Dispose();

                }

                pictureBox1.Image = Image.FromStream(ms);

            }

        }

        catch (Exception ex)

        {

            MessageBox.Show("图片加载失败: " + ex.Message);

        }

    }

}

从数据库读取:

// 假设从数据库字段获取 byte[]

byte[] imageBytes = (byte[])dataReader["ImageData"];

从网络下载:

using (WebClient client = new WebClient())

{

    byte[] imageBytes = client.DownloadData("http://example.com/image.jpg");

}


查看更多关于C#本地图片转二进制数据完整示例代码的详细内容...

  阅读:14次