/// <summary> /// Draw the image on the graphics with GDI+ blur effect /// </summary> /// <returns>false if there is no GDI+ available or an exception occured</returns> public static bool DrawWithBlur(Graphics graphics, Bitmap image, Rectangle source, Matrix transform, ImageAttributes imageAttributes, int radius, bool expandEdges) { if (!IsBlurPossible(radius)) { return(false); } var hBlurParams = IntPtr.Zero; var hEffect = IntPtr.Zero; try { // Create a BlurParams struct and set the values var blurParams = BlurParams.Create(radius, expandEdges); // Allocate space in unmanaged memory hBlurParams = Marshal.AllocHGlobal(Marshal.SizeOf(blurParams)); // Copy the structure to the unmanaged memory Marshal.StructureToPtr(blurParams, hBlurParams, true); // Create the GDI+ BlurEffect, using the Guid var status = GdipCreateEffect(BlurEffectGuid, out hEffect); if (status != GdiPlusStatus.Ok) { Log.Error().WriteLine("Couldn't create effect {0}: {1}", BlurEffectGuid, status); return(false); } // Set the blurParams to the effect status = GdipSetEffectParameters(hEffect, hBlurParams, (uint)Marshal.SizeOf(blurParams)); if (status != GdiPlusStatus.Ok) { Log.Error().WriteLine("Couldn't apply parameters: {0}", status); return(false); } // Somewhere it said we can use destinationBitmap.GetHbitmap(), this doesn't work!! // Get the private nativeImage property from the Bitmap var hBitmap = GetNativeImage(image); var hGraphics = GetNativeGraphics(graphics); var hMatrix = GetNativeMatrix(transform); var hAttributes = GetNativeImageAttributes(imageAttributes); // Create a RECT from the Rectangle NativeRectFloat sourceRectangleF = source; // Apply the effect to the bitmap in the specified area status = GdipDrawImageFX(hGraphics, hBitmap, ref sourceRectangleF, hMatrix, hEffect, hAttributes, GpUnit.UnitPixel); if (status == GdiPlusStatus.Ok) { // Everything worked, return true return(true); } Log.Error().WriteLine("Couldn't draw image: {0}", status); return(false); } catch (Exception ex) { _isBlurEnabled = false; Log.Error().WriteLine(ex, "Problem using GdipDrawImageFX: "); return(false); } finally { try { if (hEffect != IntPtr.Zero) { // Delete the effect var status = GdipDeleteEffect(hEffect); if (status != GdiPlusStatus.Ok) { Log.Error().WriteLine("Couldn't delete effect: {0}", status); } } if (hBlurParams != IntPtr.Zero) { // Free the memory Marshal.FreeHGlobal(hBlurParams); } } catch (Exception ex) { _isBlurEnabled = false; Log.Error().WriteLine(ex, "Problem cleaning up DrawWithBlur: "); } } }