I have a list of restaurant names, I need to draw these strings to a Bitmap.
I create the Bitmap, draw the text but then if I do not save the Bitmap and then load the saved file into a Bitmap before adding it to the list, the Bitmap is invalid.
Here is my code, with many names redacted for brevity, I am hoping someone can explain why and how I can avoid saving to disk:
Option Strict On
Imports System.IO
Public Class Form1
Private R As New Random
Private Places As New List(Of String)
Private Images As New List(Of Bitmap)
Private TheFont As Font = New Font("Engravers MT", 18)
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
PictureBox1.Visible = False
Using g As Graphics = Me.CreateGraphics
For Each S As String In Places ' List of Restaurant Names
Dim SF As SizeF = g.MeasureString(S, TheFont)
TextBox1.AppendText(S & " = " & SF.Width & ", " & SF.Height & vbNewLine)
PictureBox1.Size = New Size(CInt(SF.Width), CInt(SF.Height))
Using BM As Bitmap = New Bitmap(PictureBox1.Width, PictureBox1.Height)
Using gg As Graphics = Graphics.FromImage(BM)
gg.Clear(Color.White)
gg.DrawString(S, TheFont, Brushes.Black, 0, 0)
gg.Flush()
End Using
'Code that WORKS
BM.Save("D:\AAAAAA\" & S & ".jpg", Imaging.ImageFormat.Jpeg) '*************************
Images.Add(CType(Image.FromFile("D:\AAAAAA\" & S & ".jpg"), Bitmap)) '********************************
''The code above DOES WORK
'The code below DOES NOT WORK, using only one of the two at a time
'Images.Add(CType(BM, Bitmap)) '************************************
'Images.Add(BM) '************************************
'Code that DOES NOT WORK
End Using
Next
End Using
Stop ' for debugging
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
PictureBox1.Visible = True
Dim Index As Integer = R.Next(0, Images.Count)
Dim B As Bitmap = Images(Index) ' was .Clone
PictureBox1.Width = B.Width
PictureBox1.Height = B.Height
PictureBox1.Image = B
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Places.Add("Arby's")
Places.Add("Baja Fresh Mexican Grill")
Places.Add("Black Bear Diner")
Places.Add("Burger King")
Places.Add("Carl's Jr.")
Places.Add("Chick-fil-A")
End Sub
End Class