1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
|
Imports System.Drawing.Imaging
Imports System.Runtime.InteropServices.Marshal
Public Class LockBitmap
Private BaseImage As Bitmap
Private BaseImageWidth As Integer
Private BaseImageHeight As Integer
Private TotalPixels As Integer
Private ImageAddress As IntPtr
Private ImageContent As BitmapData
Private ImageBuffer() As Integer
Public Property Image() As Bitmap
' ----- User access to the relevant image.
Get
Return BaseImage
End Get
Set(ByVal Value As Bitmap)
Dim canvas As Graphics
BaseImage = New Bitmap(Value.Width, _
Value.Height, Value.PixelFormat)
canvas = Graphics.FromImage(BaseImage)
canvas.DrawImage(Value, 0, 0, _
Value.Width, Value.Height)
canvas.Dispose()
End Set
End Property
Private Sub LockTheImage()
' ----- Lock the image in memory. How much room do we need?
BaseImageWidth = BaseImage.Width
BaseImageHeight = BaseImage.Height
TotalPixels = BaseImageWidth * BaseImageHeight
' ----- Create a stable (locked) area in memory. It will store 32-bit alpha color images.
ReDim ImageBuffer(TotalPixels - 1)
ImageContent = BaseImage.LockBits( _
New Rectangle(0, 0, BaseImageWidth, _
BaseImageHeight), ImageLockMode.ReadWrite, _
PixelFormat.Format32bppArgb)
ImageAddress = ImageContent.Scan0
' ----- Associate the buffer and the locked memory.
Copy(ImageAddress, ImageBuffer, 0, TotalPixels)
End Sub
Private Sub UnlockTheImage()
' ----- Unlock the memory area.
Copy(ImageBuffer, 0, ImageAddress, TotalPixels)
Image.UnlockBits(ImageContent)
ImageContent = Nothing
ReDim ImageBuffer(0)
End Sub
Public Sub MakeOpacity(ByVal alpha As Integer)
' ----- Make a grayscale version of the image.
Dim pixelIndex As Integer
Dim thePixel As Integer
Dim alphaPart As Integer
Dim redPart As Integer
Dim greenPart As Integer
Dim bluePart As Integer
Dim y As Integer
Dim x As Integer
' ----- Lock the image for speed.
LockTheImage()
' ----- Process each pixel in the grid.
For y = 0 To BaseImageHeight - 1
For x = 0 To BaseImageWidth - 1
' ----- Locate the pixel's color.
pixelIndex = y * BaseImageWidth + x
thePixel = ImageBuffer(pixelIndex)
' ----- Extract the color values.
alphaPart = (thePixel >> 24) And &HFF
redPart = (thePixel >> 16) And &HFF
greenPart = (thePixel >> 8) And &HFF
bluePart = thePixel And &HFF
' ----- Set opacity.
alphaPart = alpha
' ----- Set the pixel.
'Retain the original color.
ImageBuffer(pixelIndex) = (alphaPart << 24) + _
(redPart << 16) + (greenPart << 8) + bluePart
Next x
Next y
' ----- Finished. Unlock the image.
UnlockTheImage()
End Sub
End Class |
Partager