This article is mainly for you to introduce the C # Lossless conversion image for the method of icon, with a certain reference value, interested in small partners can refer to
Title, the common methods on the market are:
var handle = bmp. Gethicon (); Get the icon handle return Icon.fromhandle (handle); Get an icon through a handle
The problem with this method is that if the image is a transparent background, then the edge of the resulting icon is coarse, such as the first cushion a layer of background color and then to the effect of color, very unsatisfactory, used by friends know. Not yet studied is BMP. Gethicon out of the problem, or icon.fromhandle have problems, in the future Bambo again.
The perfect conversion method is given below:
<summary>///convert image to icon///</summary>///<param name= "image" > Image object to convert to icon </param>// /<param name= "Nulltonull" > whether null is returned when image is null. False to throw a null reference exception </param>///<exception cref= "ArgumentNullException"/>public static Icon Converttoicon (Image Image, BOOL Nulltonull = False) {if (image = = null) {if (nulltonull) {return null;} throw new ArgumentNullException ("image"); } using (MemoryStream msimg = new MemoryStream (), Msico = new MemoryStream ()) {image. Save (msimg, imageformat.png); using (var bin = new BinaryWriter (Msico)) {//write icon header bin. Write ((short) 0); 0-1 Keep bin. Write ((short) 1); 2-3 file types. 1= icon, 2 = Cursor bin. Write ((short) 1); 4-5 number of images (icons can contain multiple images) bin. Write ((byte) image. Width); 6 icon Width bin. Write ((byte) image. Height); 7 Icon Height bin. Write ((byte) 0); 8 Color number (if pixel bit depth >=8, fill 0.) It is obvious that the number of colors reaching 8bpp is at least 256,byte enough to represent) the bin. Write ((byte) 0); 9 reserved. Must be 0 bin. Write ((short) 0); 10-11 Palette bin. Write ((short) 32); 12-13 bits deep bin. Write ((int) msimg.length); 14-17 Bitmap data Size bin. Write (22); 18-21 bitmap Data Start byte//write image data bin. Write (Msimg.toarray ()); Bin. Flush (); Bin. Seek (0, Seekorigin.begin); return new Icon (Msico); } }}
As the code shows, the principle of the method is:
1. Encode image as PNG first
2. Then wrap PNG as an icon
The 1th step is recoding, but PNG is lossless and the image quality is not lost in the slightest. The converted PNG is then plugged into the icon at the binary level intact. So the whole method can afford to "lossless" argument, mind the distortion of friends please rest assured use. Note: The original size is not checked and processed in the method, so please make sure that the original size is in accordance with the icon specification and re-enter; In addition, it is not responsible for destroying the original image, the caller is responsible externally.