C#byte数组与Image的相互转换实例代码
程序员文章站
2023-08-15 21:01:43
c#byte数组与image的相互转换实例代码
功能需求:
1、把一张图片(png bmp jpeg bmp gif)转换为byte数组存放到数据库。
2、把从数据库...
c#byte数组与image的相互转换实例代码
功能需求:
1、把一张图片(png bmp jpeg bmp gif)转换为byte数组存放到数据库。
2、把从数据库读取的byte数组转换为image对象,赋值给相应的控件显示。
3、从图片byte数组得到对应图片的格式,生成一张图片保存到磁盘上。
这里的image是system.drawing.image。
//get an image from file image image = image.fromfile("d:\\test.jpg"); bitmap bitmap = new bitmap("d:\\test.jpg");
以下三个函数分别实现了上述三个需求:
using system; using system.collections.generic; using system.drawing; using system.drawing.imaging; using system.io; using system.linq; using system.text; namespace netutilitylib { public static class imagehelper { /// <summary> /// convert image to byte[] /// </summary> /// <param name="image"></param> /// <returns></returns> public static byte[] imagetobytes(image image) { imageformat format = image.rawformat; using (memorystream ms = new memorystream()) { if (format.equals(imageformat.jpeg)) { image.save(ms, imageformat.jpeg); } else if (format.equals(imageformat.png)) { image.save(ms, imageformat.png); } else if (format.equals(imageformat.bmp)) { image.save(ms, imageformat.bmp); } else if (format.equals(imageformat.gif)) { image.save(ms, imageformat.gif); } else if (format.equals(imageformat.icon)) { image.save(ms, imageformat.icon); } byte[] buffer = new byte[ms.length]; //image.save()会改变memorystream的position,需要重新seek到begin ms.seek(0, seekorigin.begin); ms.read(buffer, 0, buffer.length); return buffer; } } /// <summary> /// convert byte[] to image /// </summary> /// <param name="buffer"></param> /// <returns></returns> public static image bytestoimage(byte[] buffer) { memorystream ms = new memorystream(buffer); image image = system.drawing.image.fromstream(ms); return image; } /// <summary> /// convert byte[] to a picture and store it in file /// </summary> /// <param name="filename"></param> /// <param name="buffer"></param> /// <returns></returns> public static string createimagefrombytes(string filename, byte[] buffer) { string file = filename; image image = bytestoimage(buffer); imageformat format = image.rawformat; if (format.equals(imageformat.jpeg)) { file += ".jpeg"; } else if (format.equals(imageformat.png)) { file += ".png"; } else if (format.equals(imageformat.bmp)) { file += ".bmp"; } else if (format.equals(imageformat.gif)) { file += ".gif"; } else if (format.equals(imageformat.icon)) { file += ".icon"; } system.io.fileinfo info = new system.io.fileinfo(file); system.io.directory.createdirectory(info.directory.fullname); file.writeallbytes(file, buffer); return file; } } }
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
上一篇: 六款蜂蜜自制面膜 养颜美容打造无暇肌肤