Presentation on theme: "SWT (III) VB Week 3 1 Session 7 vDisplay a text file by using a text box object vSave notes in a text file vString processing vA Simple Digital Image Management."— Presentation transcript:
SWT (III) VB Week 3 1 Session 7 vDisplay a text file by using a text box object vSave notes in a text file vString processing vA Simple Digital Image Management Program
SWT (III) VB Week 3 2 Display Text Files by Using a Text Box Object (I/III) The simplest way to display a text file in a programme is to use a text box object. You can create text box objects in a variety of sizes. Scroll bar can be added to the text box object if the text file does not fit neatly in the box. To load the contents of a text file into a text box, you need to use three statements and one function with the following corresponding keywords KeywordDescription OpenOpen a text file for input or output Line InputReads a line of input from the text file EOFChecks for the end of text file CloseClose the text file What is the difference between a text file and a document file?
SWT (III) VB Week 3 3 Display Text Files by Using a Text Box Object (II/III) Open a Text File for Input The Open Statement Open PathName For Mode As #FileNumber PathName: is a valid MicroSoft Windows pathname Mode: is a keyword indicating how the file will be used: Input, Output, Append FileNumber: is an integer from 1 to 255. The FileNumber will be associated with the file when it is open. You then use this file number in your code whenever you need to refer to the open file. A typical Open statement using a common dialog object looks like this: Open CommonDialog1.FileName For Input As #1
SWT (III) VB Week 3 4 Display Text Files by Using a Text Box Object (III/III) Public txtFileName$ Private Sub cmdDisplay_Click() txtBoxFile.Text = "" WrapChar = Chr(13) + Chr(10) If txtFileName$ <> "" Then Open txtFileName For Input As #1 End If Do Until EOF(1) Line Input #1, LineOfTxt LineOfTxt = LineOfTxt & WrapChar txtBoxFile.Text = txtBoxFile.Text & LineOfTxt Loop Close #1 End Sub Private Sub Dir1_Change() File1.Path = Dir1.Path End Sub Private Sub Drive1_Change() Dir1.Path = Drive1.Drive End Sub Private Sub File1_Click() txtFileName$ = File1.Path & "\" & File1.FileName End Sub Search for Text File and Display Its Content
SWT (III) VB Week 3 5 Create a New File on Disk Creating new files on a disk and saving data to them will be useful if you plan to generate custom reports or logs, save important calculations or values, or creating a special purpose word processor or text editor. Continuing the Image Annotation Program from Week2, we can save the annotations to a file for future use. Private Sub cmdSaveResult_Click() ResultFileName$ = InputBox _ ("Please enter the result file Name", _ "Result File Name Box") If ResultFileName$ <> "" Then ResultFileName$ = _ File1.Path & "\" & ResultFileName$ Open ResultFileName For Output As #2 End If Print #2, txtContent.Text Close #2 End Sub
SWT (III) VB Week 3 6 Processing Text Strings Sorting Text The basic concepts in sorting are simple. You draw up a list of items to sort, and then compare the items one by one until the list is sorted in ascending or descending alphabetical or numerical order. Processing Strings with Statements and Function The most common task you will do with strings is concatenating them by using the & (concatenation) operator. E.g slogan$ = “Bring” & “on the” & “circus!” The above statement concatenates three literal string expressions and assign the result (Bring on the circus!) to the string variable slogan$. You can also modify string expressions by using several special statements, functions and operators in your programme code. The following table list some of the most useful keywords.
SWT (III) VB Week 3 7 Processing Text Strings KeywordDescriptionExample UcaseChange a string’s letters to uppercaseUcase (“Kim”); return KIM LcaseChange a string’s letters to lowercaseUcase (“KIM”); return kim LenThe length (in characters) of a stringLen (“Leeds”); return 5 RightReturns a fixed no. of char from the right side of a string Right(“Computer”,4); return uter LeftReturns a fixed no. of char from the left side of a string Leftt(“Computer”,4); return Comp MidReturns a fixed number of chars in the mid from start pointMid (“Computer”, 4, 3); return put InStrFinds the starting point of one string within a larger stringstart%=InStr(”bobby”, “bob”), start%=1 StringRepeats a string of charactersString(5, “*”); returns ***** AscReturns the ASCII code of the specified letterAsc(“A”); returns 65 ChrReturns the character of the specified ASCII codeChr$(65); returns A XorPerforms an exclusive or operation on two numbers65 Xor 50 returns 115 ASCII (American Standard Code (for) Information Interchange) Before VB can compare one character to another in a sort, it must convert each character into a number by using a translation table called the ASCII character set. To compare text string or ASCII code with another, you simply use one of the six relational operators: <>, =,, =
SWT (III) VB Week 3 8 A Simple Digital Image Management Program: Introduction Perl has very powerful pattern matching functions (regular expressions). VB’s pattern matching facilities is very limited. However, the usefulness of VB is in its ability to program customised databases applications. We will study this next week. In the rest of this week’s lesson we will study how to create a simple program to manage a collections of digital images, a sort of image database. Notice that state of the art image database management is very advanced, some are even very intelligent, for example, you can query image database by example or by content, asking questions such as “Find me all images similar to this one”. If you are interested in this topic, have a look at my Webpage under research heading for more info, we have developed some very advanced technologies in this area. The idea is this: assuming that you have been on holiday in some very nice places and brought back many digital photographs of wild life. In order to be able to find them easily in a few years time, you will annotate the image by associating each image with a set of keywords, describing things such as the type of animal, many of them, where the photo was taken etc. so that you can search the images using keywords. In the examples on page 5 of this note, we already have a program which could display the image, allowed user type content description of the image and saved the location of picture and the its content descriptions. Similar to a database, we can have a record for each image. Each record will content a number of “fields”. Because we will save the records of the images in a single file, we will have to have some means to identify the head and tail of each image record. Also we have to know where in the system the image file is physically located. We also have to know the format of the content description. We can store each image record in a text file in the following format:
SWT (III) VB Week 3 9 Record Format A Simple Digital Image Management Program: Annotation (I/IV) RecordHead Image File Location (including file name) Type of animals in the image The numbers of Animals A general description of the image (some other records you can think of) RecordTail Once we have decided the record format, we can start design the program. Essentially, the program should be able to to two things: Creating the database and Query the database. To create the database, we can burrow the example on page 5. In the following example, two content description fields have been used: the animal type and the number of animals in the image. Two InputBox have been used to collect user inputs. You can easily add more record fields and change the program in a sensible manner.
SWT (III) VB Week 3 10 A Simple Digital Image Management Program: Annotation (II/IV)
SWT (III) VB Week 3 11 Private Sub cmdAnnotate_Click() NewImage$ = Annotation(ImageFileName$) txtContent.Text = txtContent.Text & NewImage End Sub Private Sub cmdReStart_Click() txtContent.Text = "" End Sub Private Sub cmdSaveResult_Click() ResultFileName$ = InputBox("Please enter _ the result file Name", "Result File Name Box") If ResultFileName$ <> "" Then ResultFileName$ = File1.Path & "\" & ResultFileName$ Open ResultFileName For Output As #2 End If Print #2, txtContent.Text Close #2 End Sub Private Sub Dir1_Change() File1.Path = Dir1.Path End Sub Private Sub Drive1_Change() Dir1.Path = Drive1.Drive End Sub Private Sub File1_Click() ImageFileName$ = _ File1.Path & "\" & File1.FileName Image1.Picture = LoadPicture(ImageFileName) End Sub A Simple Digital Image Management Program: Annotation (III/IV)
SWT (III) VB Week 3 12 Module1.bas Public ImageFileName$ Function Annotation(ImageName$) Prompt$ = "Enter the type of Anamal, e.g. Elephant, Panda etc" Content$ = InputBox(Prompt$, "Anamal Type Input Box") WrapChar$ = Chr(13) + Chr(10) 'ASCII code value 13 and 10 form a newline Character NewContent$ = Content$ & WrapChar Prompt$ = "Enter the Numbers of Anamals, 1, 2, 3 etc" Content$ = InputBox(Prompt$, "Anamal Number Input Box") NewContent$ = NewContent$ & Content$ & WrapChar ImgRecStart$ = "RecordHead" & WrapChar ImgRecEnd$ = "RecordTail" & WrapChar Annotation = ImgRecStart$ & ImageName$ & WrapChar & _ NewContent$ & ImgRecEnd$ End Function A Simple Digital Image Management Program: Annotation (IV/IV)
SWT (III) VB Week 3 13 Simple Pattern Matching Before designing the query part of the program we will first have a look how to find a string match inside a string. You can you the “Like” operator, but I cannot make it work have a go to see if you have better luck. A Simple Digital Image Management Program: String Matching (I/II)
SWT (III) VB Week 3 14 Private Sub cmdMatch_Click() TestStr$ = LCase(Label1.Caption) 'Test String is displayed in Label1 Pattern$ = LCase(InputBox("Enter a match pattern")) 'Gets matching pattern from Input Box PantternLength% = Len(Pattern$) 'Find out patern length StartPos% = InStr(TestStr$, Pattern$) 'Find the start pos If StartPos% <> 0 Then 'If matched MatchPattern$ = Mid(TestStr$, StartPos%, PantternLength%) 'the matched string from TestStr$ End If If MatchPattern$ <> "" Then Label2.Caption = _ "Match Pattern" & " " & " " & " " _ & "Success At Position" & " " & " " & StartPos% Else Label2.Caption = _ "Match Pattern" & " " & " " & "Failed" End If End Sub A Simple Digital Image Management Program: String Matching (II/II)
SWT (III) VB Week 3 15 Image Query User Interface A Simple Digital Image Management Program: Query (I/VIII)
SWT (III) VB Week 3 16 'A User Define Type to Hold Image Record Type ImgRecord Head As String ImgName As String AnimalType As String AnimalNo As String Tail As String End Type Public Index As Integer 'The total No of records Public NoImgMatched As Integer 'Total no of image Matched Public MatchedImgName(1000) As String 'Matched image names Public ImageInfo(1000) As ImgRecord 'Image record array 'Hold 1000 record in memory in anyone time Standard Module A Simple Digital Image Management Program: Query (II/VIII)
SWT (III) VB Week 3 17 Private Sub cmdLoadDb_Click() Prompt$ = "Enter the Image Record File Name" RecFileName$ = InputBox(Prompt, "Database Input") Open RecFileName$ For Input As #1 'Assuming there are fewer than 1000 records in 'the database. You can also define a dynamic 'array of records and find out exactly how many 'records in the database Index = 0 Do Until EOF(1) Line Input #1, ImageInfo(Index).Head Line Input #1, ImageInfo(Index).ImgName Line Input #1, ImageInfo(Index).AnimalType Line Input #1, ImageInfo(Index).AnimalNo Line Input #1, ImageInfo(Index).Tail Index = Index + 1 Loop Close #1 End Sub A Simple Digital Image Management Program: Query (III/VIII)
SWT (III) VB Week 3 18 Private Sub cmdSearchType_Click() Prompt = "Enter Search Pattern, e.g., Panda" SPattern$ = LCase(InputBox(Prompt, "Search Pattern")) LengthSP% = Len(SPattern$) NoImgMatched = 0 For i = 0 To Index - 1 TestStr$ = LCase(ImageInfo(i).AnimalType) StartPos% = InStr(TestStr$, SPattern$) MatchPattern$ = "" If StartPos% <> 0 Then 'If matched MatchPattern$ = Mid(TestStr$, StartPos%, LengthSP%) End If If MatchPattern$ = SPattern Then MatchedImgName(NoImgMatched) = ImageInfo(i).ImgName NoImgMatched = NoImgMatched + 1 End If Next i End Sub A Simple Digital Image Management Program: Query (IV/VIII)
SWT (III) VB Week 3 19 Private Sub cmdDisplay_Click() If NoImgMatched <> 0 Then Load Form2 For i = 0 To NoImgMatched - 1 Form2.Image1(i).Picture = _ LoadPicture(MatchedImgName(i)) Form2.Image1(i).Visible = True Form2.Label1(i).Caption = _ "No" & " " & i Form2.Label1(i).Visible = True Next i Form2.Show End If End Sub A Second Form is used to display the results A Simple Digital Image Management Program: Query (V/VIII)
SWT (III) VB Week 3 20 Control Array: is a collection of of identical interface objects. Each object in the group shares the same object name, so the entire group can be selected and defined at once. The objects in the array can be referenced individually by its index In the second form, we have created an image control array and a label control array. To create an image control array, first create one image object, then select the image object, copy and then paste. VB will ask “Do you want to create a control array”, say yes. Then paste as many times as necessary to create the required number of images objects. Assuming the image object is named image1, then each individual image is referred to as image1(0), image1(1), image1(2) … Similarly, the label control objects can be created. We have created 6 of each. A Simple Digital Image Management Program: Query (VI/VIII)
SWT (III) VB Week 3 21 Code associated with form 2 A Simple Digital Image Management Program: Query (VII/VIII)
SWT (III) VB Week 3 22 Search result for “Wild Cat” A Simple Digital Image Management Program: Query (VIII/VIII)
SWT (III) VB Week 3 23 Lab Exercise In this second assessed lab exercise, you are required to do the following A: Complete and modify the Annotation program listed in pages of this note. In particular, you are required to A(1): Add an extra field to the record, let’s call it “general description” A(2): Add a testing logic such that when an image has already been annotated, the program will output a message informing the user of this fact and do not repeat the annotation. B: Complete and modify the Query program listed in pages of this note, in particular B (1): To accommodate the changed image record format as performed in A. B(2): Complete the “Search Animal Number” function and use a third form to display the search result.