不清楚您要做什么。看起来好像您正在尝试将 .jpg 转换为 .bmp。如果是这样,你可以调用 Image 类的.Save 方法:
'Load the bitmap
Dim bm As Bitmap = Image.FromFile("C:\Users\Noah\Desktop\graphics\Grass.jpg")
'Save as .bmp
bm.Save("C:\Users\Noah\Desktop\graphics\Grass.bmp", System.Drawing.Imaging.ImageFormat.Bmp)
如果你真的需要处理像素,那么使用GetPixel 和SetPixel 会太慢。您需要使用LockBits 直接处理位图数据。像这样的:
Imports System.Drawing.Imaging
Imports System.Runtime.InteropServices
Private Sub DoGraphics()
Dim x As Integer
Dim y As Integer
'PixelSize is 3 bytes for a 24bpp Argb image.
'Change this value appropriately
Dim PixelSize As Integer = 3
'Load the bitmap
Dim bm As Bitmap = Image.FromFile("C:\Users\Noah\Desktop\graphics\Grass.jpg")
'lock the entire bitmap for editing
'You can change the rectangle to specify different parts of the image if needed.
Dim bmData As BitmapData = bm.LockBits(New Rectangle(0, 0, bm.Width, bm.Height), System.Drawing.Imaging.ImageLockMode.ReadWrite, bm.PixelFormat)
'Declare empty Color array
Dim pixels(bm.Width - 1, bm.Height - 1) As Color
'loop through the locked area of the bitmap.
For x = 0 To bmData.Width - 1
For y = 0 To bmData.Height - 1
'Get the various color offset locations for each pixel.
'This calculation is for a 24bpp rgb bitmap
Dim blueOfs As Integer = (bmData.Stride * x) + (PixelSize * y)
Dim greenOfs As Integer = blueOfs + 1
Dim redOfs As Integer = greenOfs + 1
'Read the value for each color component for each pixel
Dim red As Integer = Marshal.ReadByte(bmData.Scan0, redOfs)
Dim green As Integer = Marshal.ReadByte(bmData.Scan0, greenOfs)
Dim blue As Integer = Marshal.ReadByte(bmData.Scan0, blueOfs)
'Create a Color structure from each color component of the pixel
'and store it in the array
pixels(x, y) = Color.FromArgb(red, green, blue)
Next
Next
'Do something to the pixels array here:
For x = 0 To bmData.Width - 1
For y = 0 To bmData.Height - 1
pixels(x, y) = Color.Red
Next
Next
'Update the bitmap from the pixels array
For x = 0 To bmData.Width - 1
For y = 0 To bmData.Height - 1
'Get the various color offset locations for each pixel.
'This calculation is for a 24bpp rgb bitmap
Dim blueOfs As Integer = (bmData.Stride * x) + (PixelSize * y)
Dim greenOfs As Integer = blueOfs + 1
Dim redOfs As Integer = greenOfs + 1
'Set each component of the pixel
'There are 3 bytes that make up each pixel (24bpp rgb)
Marshal.WriteByte(bmData.Scan0, blueOfs, pixels(x, y).B)
Marshal.WriteByte(bmData.Scan0, greenOfs, pixels(x,y).G)
Marshal.WriteByte(bmData.Scan0, redOfs, pixels(x,y).R)
Next
Next
'Important!
bm.UnlockBits(bmData)
'Save the updated bitmap
bm.Save("C:\Users\Noah\Desktop\graphics\Grass.bmp", System.Drawing.Imaging.ImageFormat.Bmp)
End Sub
我希望这会有所帮助。
更新:我已更新代码以显示更改像素值。