Image Copy Issue with Ruby File method each_byte -


this problem has bugged me while.

i have jpeg file 34.6 kilobytes. let's call image a. using ruby, when copy each line of image a newly created file, called image b, copied exactly. same size image , accessible.

here code used:

image_a = file.open('image_a.jpg', 'r') image_b = file.open('image_b.jpg', 'w+')  image_a.each_line |l|   image_b.write(l) end  image_a.close image_b.close 

this code generates perfect copy of image_a image_b.

when try copy image image b, byte byte, copies file size 88.9 kilobytes rather 34.6 kilobytes. can't access image b. mac system alerted me may damaged or using file format isn't recognized.

the related code:

//same before image_a.each_byte |b|   image_b.write(b) end //same before 

why image b, when copied byte byte, larger image a? why damaged in way, shape, or form? why image same size b, when copied line line, , accessible?

my guess problem encoding issue. if so, why encoding format matter when copying byte byte if translate correct code points? code points jumbled each other parser unable differentiate between them?

do \s , \n matter? seems it. did more research , found image had 128 lines of code whereas image b had 1 line.

thanks reading!

io#each_byte iterates on bytes (aka integers). io#write, however, takes string argument. converts integer string via to_s.

given first byte in image 2551, you'd write string "255" image_b. why image_b gets larger. write number-strings it.

try following when writing bytes:

image_a.each_byte |l|   image_b.write l.chr end 

1 @stefan pointed out jpeg images start ff d8. first byte 255.


Comments

Popular posts from this blog

c++ - Creating new partition disk winapi -

Android Prevent Bluetooth Pairing Dialog -

VBA function to include CDATA -