Cant get image from resources - vb.net

My resource1 contains graphic files named dot1, dot2 , dot3 etc. and each represent image of dice wall.
My game class have method updateView()
Public Sub updateView()
Dim imageName As String
image = "dot" & ToString(dice1.getDots())
Form1.PictureBox1.Image = CType(My.Resources.ResourceManager.GetObject(imageName ), Image)
image = "dot" & ToString(dice2.getDots())
Form1.PictureBox2.Image = CType(My.Resources.ResourceManager.GetObject(imageName ), Image)
... etc.
End Sub
I want to update 5 pictureboxes on form1 with images from reasource box depending on rolled number. This code isnt working and i dont know why.
ps. sorry for bad english

It appears that you're trying to GetObject(imageName), where imageName is declared as an empty string. You can solve this two ways, either define imageName, or search for the string you create in the image variable:
Dim imageName As String
imageName = "dot" & ToString(dice1.getDots())
Form1.PictureBox1.Image = CType(My.Resources.ResourceManager.GetObject(imageName ), Image)
or,
image = "dot" & ToString(dice1.getDots())
Form1.PictureBox1.Image = CType(My.Resources.ResourceManager.GetObject(image), Image)
In either case, using Option Strict would help to solve problems like these.

Related

Taking a screenshot of only portion of the browser using selenium in VBA | "Selenium VBA"

so this one is about taking a screenshot of only a portion of the browser using Selenium in VBA. I saw there is something like
takescreenshot.hieght
takescreenshot.width
but not sure how to use these sub attributes height and width or if they will work.
Plus I have multiple images to save using different filenames automatically. I tried this but it did not work.
dim bot as chromedriver, img as selenium.image
bot.get "http:// xxxxxxx.....com"
..
..
for a = 1 to 100
set img = bot.takescreenshot(500)
img.Saveas this workbook.path & " :\" & a & ".jpg"
any suggestions please. Thanks in advance
There is unfortunately no built in function to take partial screenshots. However, you might try the following function to get an image of a specific element--please forgive any vb related mistakes I may have made as I rarely use the language.
Public Function CaptureElementScreenShot(ByVal element As HTMLElement, ByVal uniqueName As String) As Image
Dim screenshot As Screenshot = (CType(Me.driver, ITakesScreenshot)).GetScreenshot()
screenshot.SaveAsFile(filename, System.Drawing.Imaging.ImageFormat.Jpeg)
Dim img As Image = Bitmap.FromFile(uniqueName)
Dim rect As Rectangle = New Rectangle()
If element IsNot Nothing Then
Dim width As Integer = element.Size.Width
Dim height As Integer = element.Size.Height
Dim p As Point = element.Location
rect = New Rectangle(p.X, p.Y, width, height)
End If
Dim bmpImage As Bitmap = New Bitmap(img)
Dim croppedImage = bmpImage.Clone(rect, bmpImage.PixelFormat)
Return croppedImage
End Function

Visual Basic Check whether two images are the same or different

So I have a program which downloads images online and then stores them in files. But if two images have the same name, I have a piece of code which changes the file name to add a 1 to the end so that there are no errors. However, I was thinking it would be better to first check whether or not the images are the same before renaming them. And I am no way near good enough at VB as of yet to make my own image comparison code, so I looked on google and found this code but the thing is the code says that 2 identical images are different so? If anyone could have a look at the problem I would be hugely grateful.
Edit: Just for some further clarity I am comparing an image I already have stored in my folder with an image from the internet.
Re-Edit: I have found out that I have not correctly loaded one of the image variables if anybody knows what I need to change this would help? As I made the image variables the same to test and it worked fine.
Dim image1 As Bitmap = New System.Drawing.Bitmap(New IO.MemoryStream(New System.Net.WebClient().DownloadData(picture)))
Dim image2 As Bitmap = CType(Image.FromFile(path + "\" + uname + ".png", True), Bitmap)
Dim a As Boolean = AreSameImage(image1, image2)
If a Then
MsgBox("Identical image")
Else
MsgBox("Different images")
End If
Public Function AreSameImage(ByVal I1 As Image, ByVal I2 As Image) As Boolean
Dim BM1 As Bitmap = I1
Dim BM2 As Bitmap = I2
For X = 0 To BM1.Width - 1
For y = 0 To BM2.Height - 1
If BM1.GetPixel(X, y) <> BM2.GetPixel(X, y) Then
Return False
End If
Next
Next
Return True
End Function
Just out of curiosity if anyone knows how I could make it so that it checks the image against all the files in a certain folder - this would be really helpful. Thanks again!
Try to load your picture like this
Dim req As WebRequest = WebRequest.Create("http://www.google.co.il/Picture.jpg")
Dim stream As Stream = req.GetResponse().GetResponseStream()
Dim img As Image = Image.FromStream(stream)
Dim image1 As Bitmap = New Bitmap(img)
Is the path for Image2 correct?

VB Import variable then use part 1 in dropdown and display part 2 to match selection in part 1

I'm using Visual studio to build a small utility.
I'm importing variables from a text file (this makes my program expandable in the future).
I'm running into a road block trying to split the variables into usable parts.
The text file is set up as such:
Game1:flshflhdlsfsdsfs
Game2:ugdjgndrgbdvdnjd
Game3:gnnereknengievke
And the code I've gathered from searching around trying to understand how I could do this is (It's gone through multiple rewrites but I feel this is probably the closest I've gotten):
Dim value As String = File.ReadAllText("Games.txt")
Dim cut_at As String = ":"
Dim x As Integer = InStr(value, cut_at)
Dim string_before As String = value.Substring(0, x - 2)
Dim string_after As String = value.Substring(x + cut_at.Length - 1)
Games_drp.Items.AddRange(string_before)
When I run a test like this, I get an error that String_before cannot be converted to an object. I tried switching "Dim string_before As String = value.Substring(0, x - 2)" to Dim string_before As Object = value.Substring(0, x - 2), but the dropdown that's supposed to be populated by at least one of the entries before the : has absolutely nothing in it.
Being pretty new at VB and feeling like I've exhausted pretty much every way I could think of searching in google and trying to piece together various bits of information, I figure I'd try asking my own direct question:
How would I go about reading all the lines from a text file, then splitting before the : to fill a combobox, and using a label to display the string after the : matching which ever entry is selected in the dropdown.
Thanks in advance for any help.
EDIT with full code:
Imports System.IO
Public Class Saves_frm
Private Sub Saves_frm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim value As String = File.ReadAllText("Games.txt")
Dim cut_at As String = ":"
Dim x As Integer = InStr(value, cut_at)
Dim string_before As String = value.Substring(0, x - 2)
Dim string_after As String = value.Substring(x + cut_at.Length - 1)
Games_drp.Items.AddRange(string_before)
End Sub
End Class
When run as is, I get an error that 'string_before' can't be converted from a string to an object, but when I make the following change from:
Dim string_before As String = value.Substring(0, x - 2)
to:
Dim string_before As Object = value.Substring(0, x - 2)
The error goes away, but the dropdown remains blank.
It's easier to use File.ReadAllLines, as it returns an array with all the file's lines. Then, you can loop through the lines, splitting each line and adding the result to the ListBox. This should be an example, but feel free to correct any mistakes I made, as I wrote it on my phone and it's been a long time since I used VB.
Dim lines() As String = File.ReadAllLines("file.txt")
For Each line As String In lines
Dim split() As String = line.Split(":"c)
gDic.Add(split(0), split(1))
Next
EDIT: Then, you most certainly want a dictionary that contains the name and the data, check the updated code.
Then, add the names by looping through gDic.Keys. When a name is selected, access its value with gDic("key").

String to Image for a Picturebox

I have an ArrayList, each string of the ArrayList has as an entry the path of an exact image stored into my Resources (ex. Arraylist(0) = "My.Resources.img1").
I want to display some images in Pictureboxes, I thought that this code should do the trick... But there is a conflict, the app runs without errors but not a single image isn't displayed. I also checked the entries, the path are correct...
Dim res As Resources.ResourceManager
res = New Resources.ResourceManager("Picture_Quiz.Resources", System.Reflection.Assembly.GetExecutingAssembly)
'AnswersList is the ArraryList that contains the paths'
PictureBoxA.Image = resGetObject(AnswersList(0))
'I tried to use is as a String Variable instead of string from ArrayList (for no reason)'
Dim img As String
img = My.Resources.img1
PictureBoxB.Image = res.GetObject(img)
PictureBoxC.Image = res.GetObject(AnswerList(2))
PictureBoxD.Image = res.GetObject(AnswerList(3))
Any ideas what is going on?
have you considered re-writing the code so that you store an array of Enums?
Enum ResourcePics
Pic1
Pic2
Pic3
End Enum
then use a select to convert the Enum to the resource Image
Select Case AnswersList(index)
Case ResourcePics.Pic1
Return My.Resources.Pic1
Case ResourcePics.Pic2
Return My.Resources.Pic2
Case ResourcePics.Pic3
Return My.Resources.Pic3
End Select

Fitting the full File path in a label in one line by showing dots instead of some part of file path Vb.Net

Hi Guys, I have searched for different methods for this thing but couldn't get it right. Used AutoEllipses Property, Set the MaximumSize too but to no avail. How can i get a label to show the name of the file being scanned like in the pic i attached? I mean, the label should show some part from the beginning of full path of the file then some dots and then the file name with extension.
You might consider a few things; however, the range of possibilities is too large to cover, here.
There are three (3) things you need to know in order to code this properly: the actual measured size of the filepath string you are sending to the label; the measured size of the label; and the length (in characters) of your file name. There may be a fancy function that reduces the number of things you need to do and know; however, I am not about to read oodles of documentation.
All of the above things need to be dynamic so that your label can take different String objects and render them, properly.
Dim filePath As String = ""
Dim FileDirectory As String = ""
Dim fileName As String = ""
Dim filePathLength As SizeF = 0.0
Dim labelLength As Double = 0.0
Dim fileNameLength As Integer = 0.0
' Come up with a way for measuring your string:
Dim _GraphicsUnit As Graphics = Me.CreateGraphics()
' Receive your file path, here:
' and work with your file path-related Strings:
filePath = ' SOMETHING
fileDirectory = Path.GetDirectoryName(filePath)
fileName = Path.GetFileName(filePath)
fileNameLength = fileName.Length()
' Measure the length of you path
filePathLength = _GraphicsUnit.MeasureString(filePath, INSERTFONT) * _GraphicsUnit.Inches 'or other usable unit
If filePathLength > SIZEOFLABEL Then
While filePathLength > SIZEOFLABEL
' Grab a substring of the the fileDirecory, append the "...", and keep measuring until shorter
' than SIZEOFLABEL.
' Your algorithm will need to figure out how and when to re-append the fileName
End While
End If
The above is pseudo-code and is rife with errors. The above is means to demonstrate some of the tools .Net can provide you, here namely the GraphicsUnit stuff and the Path. stuff. Both of those are helpful. You will essentially be juggling those two 'things' and the SubString() method.
My attempt is to show you how to begin to think about the problem you have in front of you so that you can begin to tackle the problem (because as the comments above state, there isn't much out there that will do what you need). Your initial question does not provide any original code on which to base the above pseudo-code; in other words, I don't feel like coding your whole project but at least want to get the answers ball rolling.
An Additional Thought: .MaxLength
The above approach is quite memory intensive - requiring a lot of repetition that may not be be necessary. Simply knowing the size - in this case the MaxLength property - might be helpful. Setting the .MaxLength property of the TextBox will allow you to know how many characters can fit in the box (you'd need to consider a few other elements, e.g. font, size, etc.).
Knowing this number, you could avoid looping altogether:
SubString of fileDirectory equal to the length of .MaxLength property, remove number of characters equating to size of fileName and "..." and append the latter two.
I got an answer to this problem here Shorten The File Path and it's a very short solution as far as code is concerned.
You can use the PathCompactPathExW pInvoke method to accomplish this:
Imports System.Runtime.InteropServices
Imports System.Text
Public Class Program
<DllImport("shlwapi.dll", EntryPoint:="PathCompactPathExW", SetLastError:=True, CharSet:=CharSet.Unicode)> _
Public Shared Function PathCompactPathEx(<MarshalAs(UnmanagedType.LPTStr)> pszOut As System.Text.StringBuilder, _
<MarshalAs(UnmanagedType.LPTStr)> pszSrc As String, _
cchMax As UInteger, _
reserved As Integer) As <MarshalAs(UnmanagedType.Bool)> Boolean
End Function
Public Shared Sub Main()
Dim longPath As String = "c:\a\very\very\long\path\that\needs\to\be\shortened\by\calling\the\PathCompactpathEx.ext"
Dim length As Integer = 40
Dim result As String = CompactPath(longPath, length)
'Prints c:\a\very\very\...\PathCompactpathEx.ext
Console.WriteLine(result)
Console.ReadLine()
End Sub
Public Shared Function CompactPath(longPathName As String, wantedLength As Integer) As String
'NOTE: You need to create the builder with the required capacity before calling function.
'See http://msdn.microsoft.com/en-us/library/aa446536.aspx
Dim sb As New StringBuilder(wantedLength + 1)
PathCompactPathEx(sb, longPathName, CUInt(wantedLength + 1), 0)
Return sb.ToString()
End Function
End Class