Image和字节数组互转

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;
        }
    }
}

时间: 2025-01-14 02:02:10

Image和字节数组互转的相关文章

使用Apache的Hex类实现Hex(16进制字符串和)和字节数组的互转

包名称:org.apache.commons.codec.binary 类名称:org.apache.commons.codec.binary.Hex 1.字节数组(byte[])转为十六进制(Hex)字符串 public static String byte2hex(byte[] input) { return Hex.encodeHexString(input); } 2.十六进制字符串(Hex)转字节数字(byte[]) public static byte[] hex2byte(Stri

C#数字、16进制字符串和字节之间互转

转自http://luohonghong.blog.163.com/blog/static/78312058201242632055642/ 如下: 1.数字和字节之间互转 int num=12345; byte[] bytes=BitConverter.GetBytes(num);//将int32转换为字节数组 num=BitConverter.ToInt32(bytes,0);//将字节数组内容再转成int32类型 2.将字符串转为16进制字符,允许中文 private string Str

C#中字符数组,字节数组和string之间的转化(转)

原文链接:http://hi.baidu.com/endyli/item/7bf074945de35e1f934f41fe 来源: NDC(NetworkDiskClient)的界面和后台程序之间用Socket通信,发送命令. 环境:界面:C# winform 后台:Vc++,消息通知 网络通信,C#是通过网络字节流进行传输的,传输内容是有报文头的Protobuf.Net消息.报文头是struct结构体,先转化成 byte[],protobuf消息就先转换为内存流,再stream.ToArray

C#中结构体定义并转换字节数组

最近的项目在做socket通信报文解析的时候,用到了结构体与字节数组的转换:由于客户端采用C++开发,服务端采用C#开发,所以双方必须保证各自定义结构体成员类型和长度一致才能保证报文解析的正确性,这一点非常重要. 首先是结构体定义,一些基本的数据类型,C#与C++都是可以匹配的: [StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)] public struct Head { public

python 字符串转字节数组

场景: java加解密和python加解密互转的时候,因一些非显示字符无法确认两者是否一致,故需要打出他们的十六进制字节数组进行比较 1.python代码实现 str='123';print str.encode('hex') 结果显示:313233 2. java实现 String str="123"; StringBuffer sbf=new StringBuffer(); for(int i=0;i<str.length();i++){ Integer tmp=(int)s

整型变量(int)与字节数组(byte[])的相互转换

// int2byte.cpp : 定义控制台应用程序的入口点. // #include "stdafx.h" #include <Windows.h> /* #define MAKEWORD(a, b) ((WORD)(((BYTE)(((DWORD_PTR)(a)) & 0xff)) | ((WORD)((BYTE)(((DWORD_PTR)(b)) & 0xff))) << 8)) #define MAKELONG(a, b) ((LONG

Java中二进制、十进制、十六进制及ASCII码与String及字节数组与十六进制之间的转换

public class DigitalTrans { /** * 数字字符串转ASCII码字符串 * * @param String * 字符串 * @return ASCII字符串 */ public static String StringToAsciiString(String content) { String result = ""; int max = content.length(); for (int i = 0; i < max; i++) { char c

设计一个字节数组缓存类

转 http://blog.csdn.net/kakashi8841/article/details/42025367 版权所有,转载须注明出处! 1.为什么要 在做网络通信的时候,经常需要用到: 读:就是我们需要从网络流里面读取字节数据,并且由于分包的原因,我们需要自己缓存这些数据,而不是读完立刻丢掉. 写:我们需要把各种类型的数据变成字节写入.比如把int.string.short等变成字节数组写入流. 2.需要什么 我们需要设计一个类来实现: 支持可以不停地往这个类中添加字节 支持写入in

C# 从字节数组读取基础数据

C#的byte[]和AS3中的ByteArray都是字节数组.但是明显的AS3的ByteArray更加好用一些.因为在ByteArray当中有一个position属性,可以读取相应的字节后,自动指向下一个没有读取的字节的index.这样你永远不用自己再建一个index来手动的处理这件事情了.当然,ByteArray还有其他的一些方法和属性,是byte[]没有的.我这里强调,并非贬低C#,只是在这一块,需要做一些多余的事情,显得相当的繁琐.为此我封装了一个类库,核心类 BytesDecode 如下