# WriteImage

Use the WriteImage function Functions are tools that are available in Spreadsheet for processing and analyzing acquisitions or other results. You can add functions to your Spreadsheet job to create tool chains and produce results for specific applications. to save the current image to a local device or an FTP, SFTP, or TCP server. Optionally, you can create an SVG file, which includes the overlay graphics on top of the image.

Note:

- You can save the file to the selected Storage location while Online or Offline.
- If you configure the job A job is a user-configured program in In-Sight Spreadsheet consisting of functions and designed for specific applications. You can create and edit jobs using the In-Sight Spreadsheet interface, and load them on a vision system for deployment in a live environment. to save a large number of image files, it is recommended that you select FTP Server or SFTP Server for the Storage setting. If you save a large number of image files on an In-Sight device (for example, if the Event parameter is set to AcquireImage(A0), and the Trigger Mode of the AcquireImage function is set to Continuous), it can cause severe issues due to lack of available memory storage.

Inputs

The WriteImage function has the following syntax:

WriteImage(Image, Event, Storage, Server, User Name, Password, Block Execution, Timeout, File Path, Image Name, Image Format, Resolution, Max Append Value, Reset, Include Graphics, File Retention Enabled, Minimum Free Space, Desired Free Space)

See the table for a description of the available parameters.

Parameter | Description
Image | Specifies a reference to a cell containing an Image data structure. The default reference is to the Image data structure in cell A0.
Event | Specifies the event that forces an update. This parameter needs to refer to any event with a timestamp, for example, one of the following: A cell containing an Event function. A cell containing a Button function. Note: By default, the Event reference value is 0. If you do not change the default value, a button, labeled "Write", is automatically created and referenced when WriteImage is initially inserted into the spreadsheet.
Storage | Specifies whether you want to save the image to a local device or a file server. The save location depends on the connected device and the Storage setting of the function.
Storage Setting | Connected Device | Save Location
--- | --- | ---
Local Device | In-Sight vision system | In-Sight device Note: You must use FTP software, such as FileZilla Client, to view files. For more information, see View Files Stored on the In-Sight Vision System.
In-Sight Emulator | Host PC
PC | PC Note: Saving to a PC is only supported using an FTP/SFTP server.
FTP Server | Any device | Specified FTP server
SFTP Server | Any device | Specified SFTP server
TCP Server | Any device | Specified TCP server
Server | Specifies the server name (or IP address) on the network where the image file is written. Note: This option is enabled only when you select FTP Server, SFTP Server, or TCP Server as the Storage type. When a particular port is required, you can append it to the server name. For example, the FTP/SFTP server uses port 50021, and the IP address of the server is 192.168.0.12, enter 192.168.0.12:50021.
User Name | Specifies a valid user name for the FTP/SFTP server. When this field is left blank, admin is used. Note: This option is disabled when you select TCP Server as the Storage type. This option is enabled only when you select FTP Server or SFTP Server as the Storage type.
Password | Specifies the password for the FTP/SFTP server. The password is case-sensitive. If the FTP/SFTP server does not have a password, you can leave this field blank. Note: This option is disabled when you select TCP Server as the Storage type. This option is enabled only when you select FTP Server or SFTP Server as the Storage type. For security purposes, the entered password is masked with an asterisk (*) in the property sheet and the formula bar.
Block Execution | Specifies whether to block job execution until file transfer is complete. When disabled, the In-Sight vision system writes or transfers asynchronously.
Timeout | Specifies the time in milliseconds to block the execution. If the time to complete writing data to file or remote server exceeds this value, the tool returns #ERR to inform the job that the timeout was exceeded. Note: This option is only available if you enable the Block Execution parameter.
- File Path | Specifies the location where you want to save the file. When connected to an In-Sight emulator, and saving to the PC, you can write the file to any location where you have operating system write permissions. You can enter the following file path types to this field:
  Path | Example
  hardcoded | X:/, X:/Subdir
  UNC | //Cognex/shared/
  mapped drive | M:/Subdir
  relative | ../../Subdir
If you set a non-empty, non-absolute path, the file path is relative to the default directory. For example, relative/file.txt resolves to /home/user/relative/file.txt. If the path does not exist on the In-Sight vision system or the emulator host PC, the tool creates the folder. If the path or FTP/SFTP credentials are invalid on the FTP/SFTP server, the tool does not return #ERR. When writing a file to an FTP server, you can also specify a file path. When writing a file to an SFTP server, you can also specify an absolute file path. If you prefix the path with a tilde (~), you add the file relative to the home directory for the user of the SFTP server. Tip: Depending on your FTP/SFTP server, a valid file path can contain forward slashes or back slashes. Make sure to use a file path convention that your file server accepts. If you leave this field blank, you send the file to one of the following default locations: Local device: Default directory of the device. In-Sight emulator: %USERPROFILE%\Documents\In-Sight Spreadsheet\In-Sight Emulator FTP Server: The default directory of the specified FTP server. SFTP Server: The default directory of the specified SFTP server. Note: This option is disabled when you select TCP Server as the Storage type.
File Name | Specifies the name of the image file; also defines the name of the .svg file. Note: You can format the append value parameter of the File Name. For more information, see the Format the Value Parameter heading in this section. Follow the restrictions of legal characters according to your operating system: Legal and forbidden characters
Operating System | Forbidden Characters | Reserved Names | Other Rules
Windows | < (less-than sign) > (greater-than sign) : (colon) " (quotation mark) / (forward slash) \ (backslash) | (vertical bar) ? (question mark) * (asterisk) | CON, PRN, AUX, NUL, COM1 to COM9, LPT1 to LPT9 | File names cannot end with a space or a dot
Linux/Unix | / (forward slash) and \0 (NULL byte) | . (current directory) and .. (parent directory) | Not applicable
macOS | : (colon) and / (forward slash), depending on the context | Not applicable | Not applicable
For more information, see the documentation of your operating system.
File Type | Specifies the file format of the image.
0 = BMP (default) | Windows bitmap format (.bmp extension).
1 = JPEG | Standard encoded JPEG format (.jpg extension).
2 = PNG | Standard encoded PNG format (.png extension)
Max Append Value | The maximum number of unique image files that can be written using the specified File Name.The minimum value is 0, the maximum is 9999999, the default value is 999. A counter increments itself as each image file is written, and be added to the end of the specified File Name if no format specifier is used. Otherwise, the counter is added at the location of the format specifier. The counter automatically resets itself when it equals the Max Append Value. Existing image files on the target system is overwritten by new files of the same name. If the value is set to -1 or an out of range value, then no counter is appended to the File Name. Note: This option is disabled when you select TCP Server as the Storage type.
Reset | Restarts the counter that is appended to the specified File Name to 0. After reset, the existing image files on the target location is overwritten by new files with the same name.
0 = OFF (default) | The counter continues to increment as each image is written out, up to the Max Append Value.
1 = ON | The counter resets to 0.
Note: By default, the Reset checkbox is not selected. If you don't change the default setting, a button, labeled Reset is automatically created and referenced when the WriteImage function is initially inserted into the spreadsheet. Note: This option is disabled when you select TCP Server as the Storage type.
Overlay Graphics | Specifies whether an .svg file with the overlay graphics is created. To view the .svg file and image file, open the .svg file with a Web browser that supports the .svg file type. The .svg file contains an internal link to the acquired image associated with it, and when the browser opens the .svg file, it follows the link to open and display the acquired image along with the overlay graphics.
0 = OFF | Only the image is transferred.
1 = SVG Overlay (default) | Both image and an .svg file is transferred. When enabled, the .svg file containing the graphic overlay data is saved into the same directory specified for the images. Use a Web browser to view the overlay graphics data and images together.
2 = Render on Image | The overlay graphics are rendered on the image. No .svg file is transferred.
Note: When enabled, the .svg file uses the name specified in the File Name parameter. Due to the graphics being rendered by a third-party application, such as a Web browser, the overlay graphics data is not an exact pixel-for-pixel match.
Enable File Cleanup | When enabled, removes the oldest files when the system is below the minimum free space until the system reaches the desired free space. Note: This option is only available when the selected storage type is Local Device. When this setting is enabled, there is an additional 30-60 µs in processing time per tool execution for checking the free space on the vision system.
Minimum Free Space % | Specifies the minimum free space before cleaning up files, in a percentage value. The default is 0. If the storage reaches the specified limit, the cleanup functionality starts cleaning up older files to ensure that the minimum free space is retained.
Desired Free Space % | Specifies the amount of free space after cleaning up files, in a percentage value. The default is 50. When the vision system storage reaches the minimum free space limit, and the cleanup functionality starts cleaning up older files, the cleanup process stops when the vision system storage reaches the desired free space. Note: If the tool cannot delete enough files to reach the desired free space threshold, the function returns an error after deleting what it was able to delete. There is an additional 8 ms of approximated processing time for initiating cleanup, and an additional 0.8 ms for every file deleted.

Outputs

Returns | A WriteImage data structure that writes the image data contained in the specified Image data structure to a local device or an FTP, SFTP, or TCP server, whenever the referenced Event is updated. Returns #ERR if any input parameters are invalid, or if the file queue is full. Returns #ERR if the memory storage of the In-Sight vision system is full. Note: An invalid FTP/SFTP server path or file name does not return an #ERR. Tip: If you hover over an #ERR, the following error message is displayed:
Message | Error Reason
--- | ---
#ERR: Cannot open file: file path/file name | The specified File Path or File Name parameter is incorrect (that is, the file path is not created).
#ERR: Error 0:7:2: file path/file name | The memory storage of the vision system is full.
Results | When WriteImage is initially inserted into the spreadsheet, and if the Event and/or Reset parameters are in the default settings, the Write, Reset buttons are automatically created and referenced in the spreadsheet.

## Format the File Name Parameter

You can format the File Name parameter so that the names are aligned, by using the '|' character. If a '|' is used, the value is either zero, or blank-filled. If the character immediately following a '|' is 0, the format is zero-filled; otherwise, it is blank-filled. The next character(s) indicate how many 0 or ' ' to insert. If the filename contains multiple ‘|’ characters, the last one is used as the format indicator. If the ‘|’ character is not followed by a digit, then the ‘|’ is used as part of the name, following the restrictions of any operating system.

If File Name is set to MyImage, the saved file names are the following:

If File Name is set to MyImage|03, the saved file names are the following:

If File Name is set to MyImage|3, the saved file names are the following:

If the '|' is in the middle of the file name, the Append Value is inserted inline. For example, if File Name is set to Fail_Image|03JobX, the saved file names are the following:

## TCP Message Format

The TCP message format contains a fixed header containing the image size, image type and file name. The header is followed by the image data described by the header.

Section | Contents | Size
Header | Image Size | 4 bytes
Image Type | 4 bytes Valid values:
0 | BMP
1 | PNG
2 | JPG
9 | SVG
Image File Name | 128 bytes
Body | Image Data | Variable

Note: If the file name exceeds the fixed length when you selected TCP Server for Storage, the function returns #ERR.

The TCP server has to use the provided filename when saving image data to file when the SVG Graphics parameter is set to SVG Overlay. The metadata in the SVG requires the filename of the image for the SVG overlay to work correctly.

### Sample TCP Server

Copy

    """
    This code is provided as an example and is not guaranteed to be perfect. It is not intended for use in a production environment
    without further testing and validation. The author and the organization they represent are not responsible for any issues
    that may arise from using this code.
    """

    import socket
    import struct

    # host machine IP address and port
    server_ip = "<insert host ip>"
    server_port = 4444

    # Create a socket object
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    # Bind the socket to a specific address and port
    s.bind((server_ip, server_port))

    # Start listening for incoming connections
    s.listen(1)

    print("Server is listening on port", server_port)

    filesRecieved = 0

    try:
        # Receive data from the client
        while True:
            # Accept a connection
            print("Waiting on connection...")
            c, addr = s.accept()
            print("Got connection from", addr)

            data = ""

            while True:
                # Read header
                data = c.recv(8 + 128)
                print("Recieved header length", len(data))
                if not data:
                    print("Header not recieved, aborting read")
                    break

                fileSize = 0
                fileSizeBuffer = data[:4]
                fileSize = struct.unpack("<I", fileSizeBuffer)[0]
                print("FileSize", fileSize)
                fileTypeBuffer = data[4:8]
                fileType = struct.unpack("<I", fileTypeBuffer)[0]
                print("FileType", fileType)
                fileNameBuffer = data[8:]
                fileName = struct.unpack("128s", fileNameBuffer)[0]
                print("FileName", fileName.decode())

                # Read data in 1024 packets

                recieved = 0
                while recieved < fileSize:
                    readPacketSize = 1024
                    if fileSize - recieved < 1024:
                        readPacketSize = fileSize - recieved
                    data = c.recv(readPacketSize)
                    recieved += len(data)

                    if not data:
                        print("Got bad data packet aborting file read")
                        break

                # Save the file
                filesRecieved += 1
                print("Files Recieved", filesRecieved, "Last file size:", fileSize)
                print("")

    except KeyboardInterrupt:
        print("\nExiting")