Use Sdwebimage to load a picture, and then call the Gray method
[_iconimageview sd_setimagewithurl:[nsurl URLWithString:orderItems.iconUrl] Placeholderimage:[uiimage imagenamed:@ "Home_root_headimage"] completed:^ (UIImage *image, Nserror *error, Sdimagecachetype cachetype, Nsurl *imageURL) {
UIImage *grayimage = [self converttograyscalewith:image];
if (grayimage) {
_iconimageview.image = Grayimage;
} else {
_iconimageview.image = [UIImage imagenamed:@ "Home_root_headimage"];
}
}];
Methods of ash-induced function
-(UIImage *) Converttograyscalewith: (UIImage *) Scousimage {
Cgsize size = [scousimage size];
int width = size.width;
int height = size.height;
The pixels'll is painted to this array
uint32_t *pixels = (uint32_t *) malloc (width * height * sizeof (uint32_t));
Clear the pixels so any transparency is preserved
memset (pixels, 0, Width * height * sizeof (uint32_t));
Cgcolorspaceref colorspace = Cgcolorspacecreatedevicergb ();
Create a context with RGBA pixels
Cgcontextref context = cgbitmapcontextcreate (pixels, width, height, 8, Width * sizeof (uint32_t), ColorSpace,
Kcgbitmapbyteorder32little | Kcgimagealphapremultipliedlast);
Paint the bitmap to our context which would fill in the pixels array
Cgcontextdrawimage (context, CGRectMake (0, 0, width, height), [scousimage cgimage]);
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; + +) {
uint8_t *rgbapixel = (uint8_t *) &pixels[y * width + x];
Convert to grayscale using recommended Method:http://en.wikipedia.org/wiki/grayscale#converting_color_to_grayscale
uint32_t Gray = 0.3 * rgbapixel[red] + 0.59 * Rgbapixel[green] + 0.11 * Rgbapixel[blue];
Set the pixels to gray
Rgbapixel[red] = Gray;
Rgbapixel[green] = Gray;
Rgbapixel[blue] = Gray;
}
}
Create a new cgimageref from our context with the modified pixels
Cgimageref image = Cgbitmapcontextcreateimage (context);
We ' re do with the context, color space, and pixels
Cgcontextrelease (context);
Cgcolorspacerelease (ColorSpace);
Free (pixels);
Make a new UIImage to return
UIImage *resultuiimage = [UIImage imagewithcgimage:image];
We ' re done with the image now too
Cgimagerelease (image);
return resultuiimage;
}
How to realize the gray function of QQ avatar?