Put form image into array (VB .net) - arrays

I put two solid circles (shapes) onto a form, change their colors, and move them around. When I get them into the right position, I want to capture the full-color image of the form and put it into an array as quickly as possible. How can I do this?
Here is how I draw the objects:
I get an OvalShape from VB PowerPacks in VB2010Express and draw it as a circle on the form. After that, I adjust it in code:
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
OccultSize1 = 100
OccultSize2 = 50
OvalShape1.Width = OccultSize1
OvalShape1.Height = OccultSize1
OvalShape2.Width = OccultSize2
OvalShape2.Height = OccultSize2
OvalShape1.Left() = 155 - OvalShape1.Width / 2
OvalShape1.Top() = 153 - OvalShape1.Height / 2
OvalShape2.Left() = 155 - OvalShape2.Width / 2
OvalShape2.Top = 85 'temporary
OvalShape1.FillColor = Color.Yellow
OvalShape1.BorderColor = Color.Yellow
OvalShape2.FillColor = Color.Blue
OvalShape2.BorderColor = OvalShape2.FillColor
Label1.Text = "100"
Label2.Text = "50"
Label3.Text = "xxx"
tbHue.Value = OvalShape2.FillColor.GetHue
RadioButton1.Checked = False
RadioButton2.Checked = True
LineShape1.Visible = False
LineShape2.Visible = True
OvalShape3.Visible = False
End Sub
Here is what I have tried with DrawToBitmap (copied most of it from Stack Overflow): Button1.Click is my addition.
Private Function GetFormImage(ByRef GetBitmap As String) As Bitmap
' Make the bitmap.
Dim wid As Integer = Me.Width
Dim hgt As Integer = Me.Height
Dim bm As New Bitmap(wid, hgt)
' Draw the form onto the bitmap.
Me.DrawToBitmap(bm, New Rectangle(0, 0, wid, hgt))
bm.Save("E:\rhtempsave\bm.bmp")
' Make a smaller bitmap without borders.
wid = 240 'Me.ClientSize.Width
hgt = 320 'Me.ClientSize.Height
Dim bm2 As New Bitmap(wid, hgt)
' Get the offset from the window's corner to its client
' area's corner.
Dim pt As New Point(0, 0)
pt = PointToScreen(pt)
Dim dx As Integer = 37 'pt.X - Me.Left
Dim dy As Integer = 10 'pt.Y - Me.Top
' Copy the part of the original bitmap that we want
' into the bitmap.
Dim gr As Graphics = Graphics.FromImage(bm2)
gr.DrawImage(bm, 0, 0, New Rectangle(dx, dy, wid, hgt), _
GraphicsUnit.Pixel)
bm2.Save("E:\rhtempsave\bm2.bmp")
Return bm2
End Function
This is bm2.

For some reason, the bitmaps appeared on my disk today, but not yesterday. The only thing I did in the meantime was shutdown and restart my computer. Strangely, the bmps are not readable by Photoshop, Photoshop Elements or Win10's photo reader yet they show up as icons in the disk file dialog. Probably a header problem. I think I'm good to go with the next step of putting the bmp into an array for later retrieval. Thanks. I'm very grateful for your prompt response.

Related

RadioButton does not show up when inside a panel within a panel

This is my first question ever, so please spare me if I did something wrong.
I have a small survey form that automatically draw questions and answers from a SQL server table, and create a question label (Label_Questionnaire(i)), a panel to nest all radiobuttons for the answer of each question (Panel_Response(i)), and 3 radiobuttons(yes, no, n/a), named RadioButton_Answers(i)_1 . All questions and answers are inside a big panel (Panel_Survey) to allow user to scroll up and down (around 50 questions).
When I run the program, I can only see questions but none of the radiobuttons are showing. What I did try are:
Use .BringToFront to bring the Panel_Response and all radiobuttons to front.
Change .Parent to Controls.Add . Instead of using .Parent, I use Panel_Survey.Controls.Add(Panel_Response) and Panel_Response.Controls.Add(RadioButton_Answers_1)
Force Panel_Response.Visible = True and all radiobuttons visible = true
(I know it might sound stupid, but I'm out of trick)
How do I make those radiobuttons show up? If not, are there any better designs for this kind of survey form? Thank you for any advice, in advance!
Below is my code:
Protected Overrides Sub OnLoad(e As EventArgs)
Dim PanelCount As Integer
Dim QuestionName As String
Dim Response1 As String
Dim Response2 As String
Dim Response3 As String
Dim InitialX As Integer = Panel_Survey.Left
Dim InitialY As Integer = Panel_Survey.Top
Dim SizeX As Integer = 1000
Dim SizeY As Integer = 25
'Load the survey
Try
'Get a list of questions and answers into array of list
Dim ListofQuestionandAnswers As New List(Of List(Of String))
Dim conn As New SqlClient.SqlConnection
conn.ConnectionString = ConnectionString
Dim CommandString As String = "SELECT [QuestionID], [QuestionName] ,[Response1],[Response2],[Response3] FROM [Question_List] ORDER BY [QuestionID]"
Dim Command As New SqlClient.SqlCommand
Command.CommandText = CommandString
Command.Connection = conn
Dim dr As SqlClient.SqlDataReader
conn.Open()
dr = Command.ExecuteReader
While dr.Read
Dim ls As New List(Of String)
ls.Add(dr.GetValue(0).ToString)
ls.Add(dr.GetValue(1).ToString)
ls.Add(dr.GetValue(2).ToString)
ls.Add(dr.GetValue(3).ToString)
ls.Add(dr.GetValue(4).ToString)
ListofQuestionandAnswers.Add(ls)
End While
conn.Close()
PanelCount = ListofQuestionandAnswers.Count
For i = 0 To ListofQuestionandAnswers.Count - 1
QuestionName = ListofQuestionandAnswers(i)(1)
Response1 = ListofQuestionandAnswers(i)(2)
Response2 = ListofQuestionandAnswers(i)(3)
Response3 = ListofQuestionandAnswers(i)(4)
Dim Label_Questionnaire As New Label
Dim Panel_Response As New Panel
Dim RadioButton_Answers_1 As New RadioButton
Dim RadioButton_Answers_2 As New RadioButton
Dim RadioButton_Answers_3 As New RadioButton
'Condition the label
With Label_Questionnaire
.Parent = Panel_Survey
.Name = "Label_Questionnaire" + i.ToString
.Font = New Font("Calibri", 11, FontStyle.Regular)
.Text = QuestionName
.ForeColor = Color.Black
.Location = New Point(InitialX, InitialY)
.AutoSize = True
End With
'Condition the panel
With Panel_Response
'Panel_Survey.Controls.Add(Panel_Response)
.Parent = Panel_Survey
.Name = "Panel_Questionnaire" + i.ToString
.Location = New Point(InitialX + 880, InitialY)
.Width = 250
.Height = 25
.BringToFront()
End With
Dim j As Integer
Dim h As Integer
j = Panel_Response.Left
h = Panel_Response.Top
'Condition the radiobuttons for answers
With RadioButton_Answers_1
.Parent = Panel_Response
.Name = "RadioButton_Answers" + i.ToString + "_1"
.Font = New Font("Calibri", 11, FontStyle.Regular)
.Text = Response1
.ForeColor = Color.Black
.Location = New Point(j, h)
.AutoSize = True
h += RadioButton_Answers_1.Height
End With
With RadioButton_Answers_2
.Parent = Panel_Response
.Name = "RadioButton_Answers" + i.ToString + "_2"
.Font = New Font("Calibri", 11, FontStyle.Regular)
.Text = Response2
.ForeColor = Color.Black
.Location = New Point(RadioButton_Answers_1.Right, h)
.AutoSize = True
End With
With RadioButton_Answers_3
.Parent = Panel_Response
.Name = "RadioButton_Answers" + i.ToString + "_3"
.Font = New Font("Calibri", 11, FontStyle.Regular)
.Text = Response3
.ForeColor = Color.Black
.Location = New Point(RadioButton_Answers_2.Right, h)
.AutoSize = True
End With
InitialY = InitialY + SizeY + 10
Next
Catch ex As Exception
MessageBox.Show(String.Format("Error: {0}", ex.Message), "Error while creating questions and answers", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
Few basic problems here:
You seem to assume that when a control is placed inside a panel, it must be placed at a location relative to the form. It doesn't; it places relative to the Panel which has its own coordinate system starting at 0,0 in the top left of the panel - you initialize j and h (for locations of the radio buttons) to the Left and Top of the panel they're in, but they should be inited to 0,0 if you want the radiobuttons to start at the top left of the panel. If the Panel is placed at 300,300 on a form, and you place a radiobutton inside the panel also at 300,300 (because you copied its left and top) then the radio button will look like it's at 600,600 on the form because its at 300,300 inside a panel that is at 300,300
You only make your panel 250 wide - it's barely wide enough to show a single radio button
You increment h once, by an amount that means the next radiobutton disappears off the bottom of the panel (which is 25 pixels high)
Here:
With Panel_Response
'Panel_Survey.Controls.Add(Panel_Response)
.Parent = Panel_Survey
.Name = "Panel_Questionnaire" + i.ToString
.Location = New Point(InitialX + 880, InitialY)
.Width = 2500
.Height = 25
.BringToFront()
.BackColor = Color.Red
End With
Dim j As Integer
Dim h As Integer
j = 0
h = 0
Paste that over your app code and run it again. I made the panel BackColor red so you can more easily see where the panel is
I guess you need to decide how you want your UI to look. If the radiobuttons are laid out vertically, don't increment X when you add them to the panel (by setting the parent property). Make the panel tall enough to accommodate them (25 px not enough)
Use a FlowLayoutPaanel or TableLayoutPanel instead

itextsharp change from pdfwriter to pdfstamper to keep bookmarks in PDF

I am using iTextSharp to merge PDF documents together. My problem is I am trying to merge a large PDF which contains bookmarks. My current function is using PdfWriter to merge the documents. I know PdfStamper will work, but I cannot figure out how to change the function to work properly.
When I change PdfWriter to PdfStamper in the example below I get an error.
Code Example:
writer = PdfStamper.GetInstance(pdfDoc, New FileStream(outputPath, FileMode.OpenOrCreate))
Error Message:
'GetInstance' is not a member of 'iTextSharp.text.pdf.PdfStamper'
Here is the entire function:
Public Shared Function MergePdfFiles(ByVal pdfFiles() As String, ByVal outputPath As String) As Boolean
Dim result As Boolean = False
Dim pdfCount As Integer = 0
Dim f As Integer = 0
Dim fName As String
Dim reader As iTextSharp.text.pdf.PdfReader = Nothing
Dim pageCount As Integer = 0
Dim pdfDoc As iTextSharp.text.Document = Nothing
Dim writer As PdfWriter = Nothing
Dim cb As PdfContentByte = Nothing
Dim page As PdfImportedPage = Nothing
Dim rotation As Integer = 0
Try
pdfCount = pdfFiles.Length
If pdfCount > 1 Then
fName = pdfFiles(f)
reader = New iTextSharp.text.pdf.PdfReader(fName)
pageCount = reader.NumberOfPages
pdfDoc = New iTextSharp.text.Document(reader.GetPageSizeWithRotation(1), 18, 18, 18, 18)
writer = PdfWriter.GetInstance(pdfDoc, New FileStream(outputPath, FileMode.OpenOrCreate))
With pdfDoc
.Open()
End With
cb = writer.DirectContent
While f < pdfCount
Dim i As Integer = 0
While i < pageCount
i += 1
pdfDoc.SetPageSize(reader.GetPageSizeWithRotation(i))
pdfDoc.NewPage()
page = writer.GetImportedPage(reader, i)
rotation = reader.GetPageRotation(i)
If rotation = 90 Then
cb.AddTemplate(page, 0, -1.0F, 1.0F, 0, 0, reader.GetPageSizeWithRotation(i).Height)
ElseIf rotation = 270 Then
cb.AddTemplate(page, 0, 1.0F, -1.0F, 0, reader.GetPageSizeWithRotation(i).Width + 60, -30)
Else
cb.AddTemplate(page, 1.0F, 0, 0, 1.0F, 0, 0)
End If
End While
f += 1
If f < pdfCount Then
fName = pdfFiles(f)
reader = New iTextSharp.text.pdf.PdfReader(fName)
pageCount = reader.NumberOfPages
End If
End While
pdfDoc.Close()
result = True
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
Return False
End Try
Return result
End Function
You can't just change PdfWriter to PdfStamper. You need to create a stamper with a reader and an output stream:
PdfReader reader = new PdfReader(pathToSrc);
PdfStamper.GetInstance(reader, New FileStream(outputPath, FileMode.OpenOrCreate));
// do stuff
stamper.Close();
You don't need a Document instance if you use PdfStamper; you only need to read the documentation more closely.
All of the above is useless for you, because PdfStamper is the class to use when you manipulate a single file. If you want to merge different file, you need to use PdfCopy or PdfSmartCopy.
Please take a look at the ConcatenateBookmarks example. There's a C# example at the bottom of the page if you don't understand Java.
Browse the official iText website if you have further questions.

WPF Image resizing and storing works on most images but fails to resize or save on others

I'm trying to resize and save the 3 images as defined in the Page_load event.
Within method ResizeAndSave I have 2 methods I'm trying: FastResize and SlowResize.
When I uncomment the FastResize codeline: IMAGE 1 and 2 are saved and resized correctly. IMAGE 3 however, is saved in dimensions 625x441px and so does not respect the 200x200 box I want it to resize to.
When I instead use the SlowResize codeline: IMAGE 1 and 2 are again saved and resized correctly. IMAGE 3 however, is not saved at all.
No errors are thrown in my code. I will import images from a variety of sources so it's critical my code works on a wide range of image formats. And apparently there's something special about IMAGE 3 and I don't know what it is or how to handle it.
Here's my full code, you should be able to just copy/paste it and test it for yourself:
Imports System.Drawing
Imports System.Drawing.Imaging
Imports System.IO
Imports System.Xml
Imports System.Data.SqlClient
Imports System.Net
Imports System.Windows.Media.Imaging
Imports System.Windows.Media
Partial Class importfeeds
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'IMAGE 1
ResizeAndSave(200, 200, "https://upload.wikimedia.org/wikipedia/commons/8/82/Dell_Logo.png")
'IMAGE 2
ResizeAndSave(200, 200, "https://upload.wikimedia.org/wikipedia/commons/d/d8/Square-1_solved.jpg")
'IMAGE 3
ResizeAndSave(200, 200, "http://cdn2.emobassets.eu/media/catalog/product/1/1/1116220.jpg")
End Sub
Private Sub ResizeAndSave(ByVal maxWidth As Integer, ByVal maxHeight As Integer, ByVal imageURL As String)
Dim imgRequest As WebRequest = WebRequest.Create(imageURL)
Dim imgResponse As WebResponse = imgRequest.GetResponse()
Dim streamPhoto As Stream = imgResponse.GetResponseStream()
Dim memStream As New MemoryStream
streamPhoto.CopyTo(memStream)
memStream.Position = 0
Dim bfPhoto As BitmapFrame = ReadBitmapFrame(memStream)
Dim newWidth, newHeight As Integer
Dim scaleFactor As Double
If bfPhoto.Width > maxWidth Or bfPhoto.Height > maxHeight Then
If bfPhoto.Width > maxWidth Then
scaleFactor = maxWidth / bfPhoto.Width
newWidth = Math.Round(bfPhoto.Width * scaleFactor, 0)
newHeight = Math.Round(bfPhoto.Height * scaleFactor, 0)
End If
If newHeight > maxHeight Then
scaleFactor = maxHeight / newHeight
newWidth = Math.Round(newWidth * scaleFactor, 0)
newHeight = Math.Round(newHeight * scaleFactor, 0)
End If
End If
Dim bfResize As BitmapFrame = FastResize(bfPhoto, newWidth, newHeight)
'Dim bfResize As BitmapFrame = SlowResize(bfPhoto, newWidth, newHeight, BitmapScalingMode.Linear)
Dim baResize As Byte() = ToByteArray(bfResize)
Dim strThumbnail As String = Guid.NewGuid.ToString() + ".png"
Dim saveToPath As String = Server.MapPath(ConfigurationManager.AppSettings("products_photospath")) + "\49\" + strThumbnail
File.WriteAllBytes(saveToPath, baResize)
End Sub
Private Shared Function FastResize(bfPhoto As BitmapFrame, nWidth As Integer, nHeight As Integer) As BitmapFrame
Dim tbBitmap As New TransformedBitmap(bfPhoto, New ScaleTransform(nWidth / bfPhoto.PixelWidth, nHeight / bfPhoto.PixelHeight, 0, 0))
Return BitmapFrame.Create(tbBitmap)
End Function
'http://weblogs.asp.net/bleroy/resizing-images-from-the-server-using-wpf-wic-instead-of-gdi
Public Shared Function SlowResize(photo As BitmapFrame, width As Integer, height As Integer, scalingMode As BitmapScalingMode) As BitmapFrame
Dim group = New DrawingGroup()
RenderOptions.SetBitmapScalingMode(group, scalingMode)
group.Children.Add(New ImageDrawing(photo, New Windows.Rect(0, 0, width, height)))
Dim targetVisual = New DrawingVisual()
Dim targetContext = targetVisual.RenderOpen()
targetContext.DrawDrawing(group)
Dim target = New RenderTargetBitmap(width, height, 96, 96, PixelFormats.[Default])
targetContext.Close()
target.Render(targetVisual)
Dim targetFrame = BitmapFrame.Create(target)
Return targetFrame
End Function
Private Shared Function ToByteArray(bfResize As BitmapFrame) As Byte()
Using msStream As New MemoryStream()
Dim pbdDecoder As New PngBitmapEncoder()
pbdDecoder.Frames.Add(bfResize)
pbdDecoder.Save(msStream)
Return msStream.ToArray()
End Using
End Function
Private Shared Function ReadBitmapFrame(streamPhoto As Stream) As BitmapFrame
Dim bdDecoder As BitmapDecoder = BitmapDecoder.Create(streamPhoto, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.None)
Return bdDecoder.Frames(0)
End Function
End Class
UPDATE 1
#Hans Passant: Both your suggestions on filenaming and pixelWidth usage are spot on and helped me run this code successfully on the 3 images in the Page_load event.
I updated my original code.
However, when I run this code as part of my actual application, where I import ~100 images from a feed. The new code fails with an out of memory exception when it tries to process IMAGE 3. This happens for both FastResize and SlowResize methods. Is there something in my code or in the image in question that would cause this increase in memory usage, maybe a leak somewhere or an inefficient resizing method I use?
I have a lot of memory available on my machine, so would be very surprised if that were the problem, although I do see a big increase in the System and compressed memory (to 1.1GB) task in my Windows task manager. And still, this much memory usage would have me believe that there's something wrong in my code.
What can it be?
IMAGE 3 however, is saved in dimensions 625x441px
That is because the image is slightly different from the other ones, its DPI (dots per inch) is 300 instead of 96. Its size in pixels is 3071 x 2172 but you are using the Width and Height properties, the size in inches with a unit of 1/96" which is 982.72 x 695.04 for this image. Fix this by using the PixelWidth and PixelHeight properties instead:
Dim tbBitmap As New TransformedBitmap(bfPhoto,
New ScaleTransform(nWidth / bfPhoto.PixelWidth, nHeight / bfPhoto.PixelHeight, 0, 0))
IMAGE 3 however, is not saved at all
That doesn't add up completely, but you do have a critical bug in this statement:
Dim strThumbnail As String = "success" + Date.Now.Second.ToString + ".png"
This name is not sufficiently unique to ensure that you don't overwrite an existing file. And if the code is "fast" then Date.Now.Second will have the same value and your code overwrites a previous written image file. Note how this bug won't repro when you debug, that makes the code artificially slower and the second will be different.
You'll need a better way to name the file, Guid.NewGuid.ToString() is a very good way for example, guaranteed to be unique. Or use a simple counter that you increment for each image. You do need to focus on cleanup.

How to create an array of bits and turn them into a bitmap VB?

I want to create an array of bits and turn them into a bitmap in vb? I know how to create a bitmap like this Dim NBitmap as new bitmap(width,height), Then edit its pixels like this NBitmap.setpixel(x,y,color). This is slow however I thought that creating an array or something then converting it to a bitmap would be faster. But i don't know how... Any help would be nice!
Example:
Dim SM = DateTime.Now.Millisecond
Dim Texture As Bitmap = Image.FromFile("C:\Users\Noah\Desktop\graphics\Grass.jpg")
Dim w = 600
Dim h = 600
Dim Pixels(600, 600) As Color
Dim x = 0
Do Until x = 600
Dim y = 0
Do Until y = 600
Pixels(x, y) = Texture.GetPixel(x, y)
y += 1
Loop
x += 1
Loop
Dim EM = DateTime.Now.Millisecond
Dim FM = EM - SM
If FM < 0 Then
FM += 1000
End If
Dim FPS = 1000 / FM
Dim ETDFrame As New Bitmap(600, 600)
ETDFrame.image = Pixels().convertBMP
I know that this code dosen't work but if gives an example if what i want.My goal is to create a new bitmap and edit all the pixels super fast, fast enough for a 3d game...
It's not clear what you are trying to do. It appears as if you are trying to convert a .jpg to a .bmp. If that is so, you can just call the .Save method of the Image class:
'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)
If you really need to work with the pixels, then using GetPixel and SetPixel will be too slow. You need to use LockBits to work directly with the bitmap data. Something like this:
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
I hope this helps.
UPDATE: I have updated the code to show changing the pixel values.
Unfortunately, there isn't a property of the Bitmap class that returns an array/list of all the pixel colors, so you can't set them all at once.The Microsoft documentation page actually provides example code getting and setting pixel colors in two nested loops, much like you're already doing.
If your end goal is to store the pixel information to pass to another Bitmap, I would suggest the Clone method. Rather than expend the time and effort of extracting the data into your own format, just use the one that's already provided. The predefined methods are almost always the most efficient, so this should be your best bet for performance.
If you truly must store the colors in an array, then you'll have to write a method to loop through every color and use SetPixel one pixel at a time. This sounds like exactly what you're doing now though, so this won't save any time.

How to display part of an image using a for loop from a picturebox array

There may be a simple answer but i have tried quite a few things and nothing seems to work unless i just manually display the images but what i want is to use this sub for other pictures as well which i will fix later once i get it to display these images. My code is as follows
Private Sub updateStandardToolbar()
'Draws the sprites to the pictureboxes
Dim bit As New Bitmap(gridSize, gridSize)
Dim dest_rect As Rectangle = New Rectangle(0, 0, gridSize, gridSize)
Dim i As Integer = 0
' Associate a Graphics object with the Bitmap
Dim gr As Graphics = Graphics.FromImage(bit)
For y As Integer = 0 To standardNum.Y
For x As Integer = 0 To standardNum.X
Call getSrcRect(x, y)
'Copy that part of the image.
gr.DrawImage(bmpStandardTile, dest_rect, src_rect, GraphicsUnit.Pixel)
'Display the result.
pb(i).Image = bit
i += 1
Next
Next
End Sub
The problem with this code is all the pictureboxes (pb()) displays the same picture which is the last one on my image. StandardNum.x and standardNum.y are variables which hold 3 and 1 respectively. bmpStandardTile is the image I want to copy from and hopefully dest_rect and src_rect is self explanatory =). Any helps is appreciated.
Oh. I just found the answer to my own problem after looking at why the pictureboxes displays the same image. Here is my code and how i fixed it if anyone else has a similar or the same problem.
Private Sub updateStandardToolbar()
'Draws the sprites to the pictureboxes
Dim bit As Bitmap
Dim dest_rect As Rectangle = New Rectangle(0, 0, gridSize, gridSize)
Dim i As Integer = 0
' Associate a Graphics object with the Bitmap
'Dim gr As Graphics
'For u As Integer = 0 To maxPics
' bit = New Bitmap(gridSize, gridSize)
'Next
For y As Integer = 0 To standardNum.Y
For x As Integer = 0 To standardNum.X
bit = New Bitmap(gridSize, gridSize)
Dim gr As Graphics = Graphics.FromImage(bit)
Call getSrcRect(x, y)
'Copy that part of the image.
gr.DrawImage(bmpStandardTile, dest_rect, src_rect, GraphicsUnit.Pixel)
'Display the result.
pb(i).Image = bit
i += 1
Next
Next
End Sub
The answer was actually very simple. Silly me. I forgot to clear the bitmap image so it will not change the image which the last picturebox was using.
bit = New Bitmap(gridSize, gridSize)
Anyway Learnt from my mistakes =)

Resources