Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to read a image file(jpg or bitmap) and put data into byte array

Status
Not open for further replies.

fz315

Programmer
Oct 29, 2004
6
CA
Hi, How to read a image file(jpg or bitmap) and put data into byte array, then send it via socket?using perl, win2000. Tons of thanks!
 
read file, one byte at a time or however many bytes you want - using read()
PerlDocs said:
read FILEHANDLE,SCALAR,LENGTH,OFFSET

read FILEHANDLE,SCALAR,LENGTH

Attempts to read LENGTH characters of data into variable SCALAR from the specified FILEHANDLE. Returns the number of characters actually read, 0 at end of file, or undef if there was an error (in the latter case $! is also set). SCALAR will be grown or shrunk so that the last character actually read is the last character of the scalar after the read.
An OFFSET may be specified to place the read data at some place in the string other than the beginning. A negative OFFSET specifies placement at that many characters counting backwards from the end of the string. A positive OFFSET greater than the length of SCALAR results in the string being padded to the required size with "\0" bytes before the result of the read is appended.

The call is actually implemented in terms of either Perl's or system's fread() call. To get a true read(2) system call, see sysread.

Note the characters: depending on the status of the filehandle, either (8-bit) bytes or characters are read. By default all filehandles operate on bytes, but for example if the filehandle has been opened with the :utf8 I/O layer (see open, and the open pragma, the open manpage), the I/O will operate on UTF-8 encoded Unicode characters, not bytes. Similarly for the :encoding pragma: in that case pretty much any characters can be read.
Then put the character you read into an element of an array, like this:
Code:
open(FH,'somepic.jpg');
binmode(FH); # if you're on Windows
$i=0;
while(read(FH,$char,1)){
[tab]$array[$i++]=$char;
}
close(FH);
That will get whole file into araay - get that working (write it out to another file to make sure it's same as original) and then think about xfer using sockets.

Once you have sockets based xfer working, revisit file-reading routine to make it read more than one byte at once. Example above will be slow but has merit of being easy to understand. It will also need some error checking, after the open() for instance.

Mike

To err is human,
but to really foul things up -
you require a man Mike.

Want to get great answers to your Tek-Tips questions? Have a look at faq219-2884

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top