图片转成二进制并且压缩字符串
今天工作需要写了一个把图片转成字符串,并且压缩的小功能,其中用到了多线程去转换字符串,感觉写的还是不错的,拿出来分享一下
1 /// <summary> 2 /// 创建多核任务 3 /// </summary> 4 /// <param name="bytimages"></param> 5 /// <param name="count">创建几个核</param> 6 public string[] MoreTask(byte[] bytImages,int count) 7 { 8 string[] temps=new string[count]; 9 Task[] tasks = new Task[count]; 10 int length = bytImages.Length; 11 for (int i = 0; i < count; i++) 12 { 13 int a = i; 14 tasks[a] = Task.Factory.StartNew(() => dosomething(out temps[a], (length / count) * a, (length / count) * (a + 1), bytImages)); 15 // tasks[i] = Task.Factory.StartNew(() => dosomething(out temps[i], (length / count) * i, (length / count) * (i + 1), bytImages)); 16 } 17 Task.WaitAll(tasks); 18 19 return temps; 20 }
主要就是利用这个方法开启任意多个线程去处理转换任务。
然后分享一下字符串压缩的方法
using System; using System.Collections.Generic; using System.Data; using System.IO; using System.IO.Compression; using System.Linq; using System.Text; using System.Web; namespace testImage { public class ZipHelper { public static string Compress(string str) { //因输入的字符串不是Base64所以转换为Base64,因为HTTP如果不传递Base64则会发生http 400错误 return Convert.ToBase64String(Compress(Convert.FromBase64String(Convert.ToBase64String(Encoding.Default.GetBytes(str))))); } public static string Decompress(string str) { return Encoding.Default.GetString(Decompress(Convert.FromBase64String(str))); } public static byte[] Compress(byte[] bytes) { using (MemoryStream ms = new MemoryStream()) { GZipStream Compress = new GZipStream(ms, CompressionMode.Compress); Compress.Write(bytes, 0, bytes.Length); Compress.Close(); return ms.ToArray(); } } public static byte[] Decompress(Byte[] bytes) { using (MemoryStream tempMs = new MemoryStream()) { using (MemoryStream ms = new MemoryStream(bytes)) { GZipStream Decompress = new GZipStream(ms, CompressionMode.Decompress); Decompress.CopyTo(tempMs); Decompress.Close(); return tempMs.ToArray(); } } } } }
主要代码就在这里了