winform下图片文件与byte[]互转

本文介绍了一种将图片转换为二进制数据流的方法,并提供了相应的C#代码实现。包括从图片获取byte流、选择图片文件并转换为byte流及通过byte流还原图片的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

    用数据库存储图片乃至文件主要有两种方式,存储byte串和存储文件路径。虽然byte串存多了数据库没准很快会被撑出问题或需要维护,但是数据量比较小时反而容易保证数据安全。

using System;
using System.Data;
using System.Windows.Forms;
using System.IO;
using System.Drawing.Imaging;
using System.Drawing;


public class PicToByte
{
    /// <summary>
    /// 获得指定图片的二进制数据流
    /// </summary>
    /// <param name="img"></param>
    /// <returns></returns>
    static public byte[] GetBinaryPhoto(Image img)
    {
        MemoryStream stream = new MemoryStream();
        img.Save(stream, ImageFormat.Bmp);
        BinaryReader br = new BinaryReader(stream);
        byte[] photo = stream.ToArray();
        stream.Close();
        return photo;
    }

    /// <summary>
    /// 找到指定图片文件并获得其二进制数据流
    /// </summary>
    /// <returns></returns>
    static public byte[] GetBinaryPhoto()
    {
        OpenFileDialog openDialog = new OpenFileDialog();
        openDialog.Filter = "图像文件(*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF|所有文件(*.*)|*.*";
        if (openDialog.ShowDialog() != DialogResult.OK)
        {
            return null;
        }

        Image img = new Bitmap(openDialog.FileName);
        MemoryStream stream = new MemoryStream();
        img.Save(stream, ImageFormat.Bmp);
        BinaryReader br = new BinaryReader(stream);
        byte[] photo = stream.ToArray();
        stream.Close();
        return photo;
    }

    /// <summary>
    /// 用指定二进制数据流生成图片
    /// </summary>
    /// <param name="photo"></param>
    /// <returns></returns>
    static public Image GetGraphicPhoto(byte[] photo)
    {
        MemoryStream ms = new MemoryStream(photo);
        ms.Position = 0;
        Image graphicPhoto = Image.FromStream(ms);
        ms.Close();
        return graphicPhoto;
    }

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值