欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C# 将字节流转换为图片的实例方法

程序员文章站 2023-12-14 08:52:46
复制代码 代码如下:usingsystem; usingsystem.collections.generic; usingsystem.linq; usingsystem....

复制代码 代码如下:

usingsystem;
usingsystem.collections.generic;
usingsystem.linq;
usingsystem.text;
usingsystem.drawing;
usingsystem.io;
namespacemicrosoft.form.base
{
    classimagetobyte
    {
        /// <summary>
        /// 图片转换成字节流
        /// </summary>
        /// <param name="img">要转换的image对象</param>
        /// <returns>转换后返回的字节流</returns>
        publicstaticbyte[] imgtobyt(image img)
        {
            memorystream ms = newmemorystream();
            byte[] imagedata = null;
            img.save(ms, system.drawing.imaging.imageformat.jpeg);
            imagedata = ms.getbuffer();
            returnimagedata;            
        }
        /// <summary>
        /// 字节流转换成图片
        /// </summary>
        /// <param name="byt">要转换的字节流</param>
        /// <returns>转换得到的image对象</returns>
        publicstaticimage byttoimg(byte[] byt)
        {
            memorystream ms = newmemorystream(byt);
            image img = image.fromstream(ms);
            returnimg;
        }
        //
        /// <summary>
        /// 根据图片路径返回图片的字节流byte[]
        /// </summary>
        /// <param name="imagepath">图片路径</param>
        /// <returns>返回的字节流</returns>
        privatestaticbyte[] getimagebyte(stringimagepath)
        {
            filestream files = newfilestream(imagepath, filemode.open);
            byte[] imgbyte = newbyte[files.length];
            files.read(imgbyte, 0, imgbyte.length);
            files.close();
            returnimgbyte;
        }
    }
}

上一篇:

下一篇: