SWT (III) VB Week 3 1 Session 7 vDisplay a text file by using a text box object vSave notes in a...

24
SWT (III) VB Week 3 1 Session 7 Display a text file by using a text box object Save notes in a text file String processing A Simple Digital Image Management Program

Transcript of SWT (III) VB Week 3 1 Session 7 vDisplay a text file by using a text box object vSave notes in a...

Page 1: 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.

SWT (III) VB Week 3 1

Session 7

Display a text file by using a text box object

Save notes in a text file

String processing

A Simple Digital Image Management Program

Page 2: 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.

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 thetext 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

Keyword Description

Open Open a text file for input or outputLine Input Reads a line of input from the text fileEOF Checks for the end of text fileClose Close the text file

What is the difference between a text file and a document file?

Page 3: 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.

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 pathnameMode: is a keyword indicating how the file will be used: Input, Output, AppendFileNumber: 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

Page 4: 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.

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$ <> "" ThenOpen txtFileName For Input As #1End IfDo Until EOF(1)Line Input #1, LineOfTxtLineOfTxt = LineOfTxt & WrapChartxtBoxFile.Text = txtBoxFile.Text & LineOfTxtLoopClose #1End Sub

Private Sub Dir1_Change() File1.Path = Dir1.PathEnd Sub

Private Sub Drive1_Change()Dir1.Path = Drive1.DriveEnd Sub

Private Sub File1_Click() txtFileName$ = File1.Path & "\" & File1.FileNameEnd Sub

Search for Text File and Display Its Content

Page 5: 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.

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 creatinga 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$ <> "" ThenResultFileName$ = _

File1.Path & "\" & ResultFileName$Open ResultFileName For Output As #2End IfPrint #2, txtContent.TextClose #2End Sub

Page 6: 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.

SWT (III) VB Week 3 6

Processing Text Strings

Sorting TextThe 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 FunctionThe 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, functionsand operators in your programme code. The following table list some of the most useful keywords.

Page 7: 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.

SWT (III) VB Week 3 7

Processing Text Strings

Keyword Description Example

Ucase Change a string’s letters to uppercase Ucase (“Kim”); return KIMLcase Change a string’s letters to lowercase Ucase (“KIM”); return kimLen The length (in characters) of a string Len (“Leeds”); return 5Right Returns a fixed no. of char from the right side of a string Right(“Computer”,4); return uterLeft Returns a fixed no. of char from the left side of a string Leftt(“Computer”,4); return CompMid Returns a fixed number of chars in the mid from start point Mid (“Computer”, 4, 3); return putInStr Finds the starting point of one string within a larger string start%=InStr(”bobby”, “bob”), start%=1String Repeats a string of characters String(5, “*”); returns *****Asc Returns the ASCII code of the specified letter Asc(“A”); returns 65Chr Returns the character of the specified ASCII code Chr$(65); returns AXor Performs an exclusive or operation on two numbers 65 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 characterinto 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 sixrelational operators: <>, =, <, >, <=, >=

Page 8: 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.

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 matchingfacilities 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 willstudy how to create a simple program to manage a collections of digital images, a sort ofimage database. Notice that state of the art image database management is very advanced, some areeven 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 broughtback 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 theits 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 imagerecord in a text file in the following format:

Page 9: 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.

SWT (III) VB Week 3 9

Record Format

A Simple Digital Image Management Program: Annotation (I/IV)

RecordHeadImage File Location (including file name)Type of animals in the imageThe numbers of AnimalsA 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 inthe image. Two InputBox have been used to collect user inputs. You can easily add more recordfields and change the program in a sensible manner.

Page 10: 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.

SWT (III) VB Week 3 10

A Simple Digital Image Management Program: Annotation (II/IV)

Page 11: 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.

SWT (III) VB Week 3 11

Private Sub cmdAnnotate_Click() NewImage$ = Annotation(ImageFileName$) txtContent.Text = txtContent.Text & NewImageEnd 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$ <> "" ThenResultFileName$ = File1.Path & "\" & ResultFileName$Open ResultFileName For Output As #2End IfPrint #2, txtContent.TextClose #2End Sub

Private Sub Dir1_Change() File1.Path = Dir1.PathEnd Sub

Private Sub Drive1_Change()Dir1.Path = Drive1.DriveEnd 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)

Page 12: 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.

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)

Page 13: 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.

SWT (III) VB Week 3 13

Simple Pattern Matching

Before designing the query part of the program we will first have a look howto find a string match inside a string.

You can you the “Like” operator, but I cannot make it workhave a go to see if you have better luck.

A Simple Digital Image Management Program: String Matching (I/II)

Page 14: 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.

SWT (III) VB Week 3 14

Private Sub cmdMatch_Click()TestStr$ = LCase(Label1.Caption)'Test String is displayed in Label1Pattern$ = LCase(InputBox("Enter a match pattern"))'Gets matching pattern from Input BoxPantternLength% = Len(Pattern$) 'Find out patern lengthStartPos% = InStr(TestStr$, Pattern$) 'Find the start posIf StartPos% <> 0 Then 'If matchedMatchPattern$ = Mid(TestStr$, StartPos%, PantternLength%)'the matched string from TestStr$End IfIf MatchPattern$ <> "" ThenLabel2.Caption = _ "Match Pattern" & " " & "<" & Pattern$ & ">" & " " _ & "Success At Position" & " " & " " & StartPos%ElseLabel2.Caption = _"Match Pattern" & " " & "<" & Pattern$ & ">" & "Failed"End IfEnd Sub

A Simple Digital Image Management Program: String Matching (II/II)

Page 15: 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.

SWT (III) VB Week 3 15

Image Query User Interface

A Simple Digital Image Management Program: Query (I/VIII)

Page 16: 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.

SWT (III) VB Week 3 16

'A User Define Type to Hold Image RecordType ImgRecord Head As String ImgName As String AnimalType As String AnimalNo As String Tail As StringEnd Type

Public Index As Integer 'The total No of recordsPublic NoImgMatched As Integer 'Total no of image MatchedPublic MatchedImgName(1000) As String 'Matched image namesPublic 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)

Page 17: 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.

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 databaseIndex = 0Do Until EOF(1)Line Input #1, ImageInfo(Index).HeadLine Input #1, ImageInfo(Index).ImgNameLine Input #1, ImageInfo(Index).AnimalTypeLine Input #1, ImageInfo(Index).AnimalNoLine Input #1, ImageInfo(Index).TailIndex = Index + 1LoopClose #1End Sub

A Simple Digital Image Management Program: Query (III/VIII)

Page 18: 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.

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 = 0For 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 IfNext iEnd Sub

A Simple Digital Image Management Program: Query (IV/VIII)

Page 19: 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.

SWT (III) VB Week 3 19

Private Sub cmdDisplay_Click()If NoImgMatched <> 0 ThenLoad Form2For i = 0 To NoImgMatched - 1Form2.Image1(i).Picture = _LoadPicture(MatchedImgName(i))Form2.Image1(i).Visible = TrueForm2.Label1(i).Caption = _ "No" & " " & iForm2.Label1(i).Visible = TrueNext iForm2.ShowEnd IfEnd Sub

A Second Form is used to displaythe results

A Simple Digital Image Management Program: Query (V/VIII)

Page 20: 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.

SWT (III) VB Week 3 20

Control Array: is a collection of of identical interface objects. Each object in the groupshares 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 pasteas many times as necessary to create the required number of images objects. Assuming the imageobject is named image1, then each individual image is referred to asimage1(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)

Page 21: 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.

SWT (III) VB Week 3 21

Code associated with form 2

A Simple Digital Image Management Program: Query (VII/VIII)

Page 22: 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.

SWT (III) VB Week 3 22

Search result for “Wild Cat”

A Simple Digital Image Management Program: Query (VIII/VIII)

Page 23: 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.

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 9 - 12 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 15 - 22 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.

Page 24: 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.

SWT (III) VB Week 3 24