At work today, I need to write a small function that converts an image into a string and compresses it. I used multiple threads to convert the string. I think it is good to write it. I 'd like to share it with you.
1 /// <summary> 2 /// create a multi-core task 3 /// </Summary> 4 /// <Param name = "bytimages"> </param> 5/ // <Param name = "count"> Create several cores </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}
This method is used to enable any number of threads to process conversion tasks.
Then share the string Compression Method
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) {// converted to base64 because the input string is not base64, because if base64 is not passed in HTTP, the HTTP 400 Error return convert will occur. 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 ();}}}}}
The main code is here.