byte[]与string转换

参考网址:https://www.cnblogs.com/xskblog/p/6179689.html

1、使用System.Text.Encoding.Default,System.Text.Encoding.ASCII,System.Text.Encoding.UTF8等。还可以使用System.Text.Encoding.UTF8.GetString(bytes).TrimEnd('\0')给字符串加上结束标识。(试用感觉还可以,编码方式需对应上)

还可以指定编码方式:System.Text.Encoding.GetEncoding("gb2312").GetBytes(str);

字符串是乱码,但数据没丢失

string  str    = System.Text.Encoding.UTF8.GetString(bytes);
byte[] decBytes = System.Text.Encoding.UTF8.GetBytes(str);

2、没有使用,不知道效果如何

string    str    = BitConverter.ToString(bytes);
String[] tempArr = str.Split('-');
byte[] decBytes = new byte[tempArr.Length];
for (int i = ; i < tempArr.Length; i++)
{
decBytes[i] = Convert.ToByte(tempArr[i], );
}

3、此方法里可能会出现转换出来的string可能会包含 '+','/' , '=' 所以如果作为url地址的话,需要进行encode(具体如何没有尝试,因为我并不是转换的网址,感觉用着还可可以,我用来存数据库了)   出现数据丢失

string str      = Convert.ToBase64String(bytes);
byte[] decBytes = Convert.FromBase64String(str);

  图片到byte[]再到base64string的转换(备用)

//在C#中
//图片到byte[]再到base64string的转换:
Bitmap bmp = new Bitmap(filepath);
MemoryStream ms = new MemoryStream();
bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
byte[] arr = new byte[ms.Length];
ms.Position = ;
ms.Read(arr, , (int)ms.Length);
ms.Close();
string pic = Convert.ToBase64String(arr); //base64string到byte[]再到图片的转换:
byte[] imageBytes = Convert.FromBase64String(pic);
//读入MemoryStream对象
MemoryStream memoryStream = new MemoryStream(imageBytes, , imageBytes.Length);
memoryStream.Write(imageBytes, , imageBytes.Length);
//转成图片
Image image = Image.FromStream(memoryStream); //现在的数据库开发中:图片的存放方式一般有CLOB:存放base64string BLOB:存放byte[]
// 一般推荐使用byte[]。因为图片可以直接转换为byte[]存放到数据库中若使用base64string 还需要从byte[]转换成base64string 。更浪费性能。

4、此方法会自动编码url地址的特殊字符,可以直接当做url地址使用。但需要依赖System.Web库才能使用。

string  str    = HttpServerUtility.UrlTokenEncode(bytes);
byte[] decBytes = HttpServerUtility.UrlTokenDecode(str);

5、自己写方法 (出现数据丢失)

 public static string ByteToString(byte[] bytes)
{ StringBuilder strBuilder = new StringBuilder(); foreach (byte bt in bytes)
{ strBuilder.AppendFormat("{0:X2}", bt); } return strBuilder.ToString(); } public static byte[] StringToByte(string str)
{ byte[] bytes = new byte[str.Length / ]; for (int i = ; i < str.Length / ; i++)
{ int btvalue = Convert.ToInt32(str.Substring(i * , ), ); bytes[i] = (byte)btvalue; } return bytes; }

byte[]与Image转换

(参考网址:http://www.cnblogs.com/luxiaoxun/p/3378416.html)

1、把一张图片(png bmp jpeg bmp gif)转换为byte数组存放到数据库。

2、把从数据库读取的byte数组转换为Image对象,赋值给相应的控件显示。

3、从图片byte数组得到对应图片的格式,生成一张图片保存到磁盘上。

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(, SeekOrigin.Begin);
ms.Read(buffer, , 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;
}
}
}

关于byte[]与string、Image转换的更多相关文章

  1. C# Byte[] 转String 无损转换

    C# Byte[] 转String 无损转换 转载请注明出处 http://www.cnblogs.com/Huerye/ /// <summary> /// string 转成byte[ ...

  2. Java - byte[] 和 String互相转换

    通过用例学习Java中的byte数组和String互相转换,这种转换可能在很多情况需要,比如IO操作,生成加密hash码等等. 除非觉得必要,否则不要将它们互相转换,他们分别代表了不同的数据,专门服务 ...

  3. Golang的Json encode/decode以及[]byte和string的转换

    使用了太长时间的python,对于强类型的Golang适应起来稍微有点费力,不过操作一次之后发现,只有这么严格的类型规定,才能让数据尽量减少在传输和解析过程中的错误.我尝试使用Golang创建了一个公 ...

  4. [转]关于网络通信,byte[]和String的转换问题

    最近的项目中要使用到把byte[]类型转换成String字符串然后通过网络发送,但发现发现出去的字符串和获取的字符串虽然是一样的,但当用String的getBytes()的方法得到的byte[]跟原来 ...

  5. C#中byte[]与string的转换

    1.        System.Text.UnicodeEncoding converter = new System.Text.UnicodeEncoding();        byte[] i ...

  6. golang []byte和string的高性能转换

    golang []byte和string的高性能转换 在fasthttp的最佳实践中有这么一句话: Avoid conversion between []byte and string, since ...

  7. C#图像处理:Stream 与 byte[] 相互转换,byte[]与string,Stream 与 File 相互转换等

    C# Stream 和 byte[] 之间的转换 一. 二进制转换成图片 MemoryStream ms = new MemoryStream(bytes); ms.Position = 0; Ima ...

  8. 如何在Byte[]和String之间进行转换

    源自C#与.NET程序员面试宝典. 如何在Byte[]和String之间进行转换? 比特(b):比特只有0 1,1代表有脉冲,0代表无脉冲.它是计算机物理内存保存的最基本单元. 字节(B):8个比特, ...

  9. go byte 和 string 类型之间转换

    string 不能直接和byte数组转换 string可以和byte的切片转换 1,string 转为[]byte var str string = "test" var data ...

随机推荐

  1. Python 的 Magic Methods 指南(转)

    介绍 本指南是数月博客的总结.主题是魔术方法. 什么是魔术方法呢?它们是面向对象Python语言中的一切.它们是你可以自定义并添加“魔法”到类中的特殊方法.它们被双下划线环绕(比如__init__或_ ...

  2. H3C S5120-52P-WiNet交换机配置

    配置console口登录验证密码 <H3C>system-view [H3C]user-interface aux 0 [H3C-ui-aux0]authentication-mode p ...

  3. Oracle中add_months()函数的用法

    查询当前时间1个月以前的时间: select add_months(sysdate,-1) from dual; 查询当前时间1个月以后的时间: select add_months(sysdate,1 ...

  4. 《转载》python爬虫实践之模拟登录

    有些网站设置了权限,只有在登录了之后才能爬取网站的内容,如何模拟登录,目前的方法主要是利用浏览器cookie模拟登录.   浏览器访问服务器的过程   在用户访问网页时,不论是通过URL输入域名或IP ...

  5. QT textBrowser 使用

    使用环境: VS2010 & QT Designer5 1. 在QT Designer 拖入  textBrowser,点击右键属性获得 name值 2. 在程序使用的地方 加入  ui.te ...

  6. DDoS(Distributed Denial of Service,分布式拒绝服务)

    DDoS:Distributed Denial of Service,即分布式拒绝服务攻击. 借助于客户/服务器技术,将多个计算机联合起来作为攻击平台,对一个或多个目标发动DDoS攻击,从而成倍地提高 ...

  7. thinkphp5---如何使用公共类

    在进行项目开发的时候,有很多的类是前后台以及其他模块都会使用的,例如验证码,上传类,密码加密的类等以及一些其他的第三方类库,如何在项目中提取这些公共的类呢? 具体方法: 例如:我在这里定义上传的类,里 ...

  8. 关于pyinstall打包时的依赖问题

    前几天写了一个人脸表情分析的小程序,想用pyinstall打包成一个可以移植的小软件.因为之前用过pyinstall,所以这次使用同样的方法对我的程序进行打包: [pyinstaller -F --i ...

  9. collections模块和os模块

    collections模块 在内置数据类型(dict.list.set.tuple)的基础上,collections模块还提供了几个额外的数据类型:Counter.deque.defaultdict. ...

  10. 10.23 crm(3)

    2018-10-23 20:34:30 继续增加新的功能!在代码注释里面有! 越努力,越幸运!永远不要高估自己! 还有明天再加上rbca权限管理系统就完美了! 然后crm做完,再过几天不挂针一切好了也 ...