Read in a general binary file (for example, but not exclusively a jpeg file), make a modification and write a new file out verbatim--no altered bytes.
5 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Charles Kluepfel
el 28 de Jul. de 2023
Comentada: Alexander
el 31 de Jul. de 2023
Someone has written a Python program that I would like to translate into MATLAB:
There are stereoscopic (3D) files that are just concatenated jpegs. There are two FF D8 byte pairs signifying the beginning of a jpeg. The software produces separate jpegs for each of the two concatenated jpegs.
My program reads in the file with
bytes=fileread(infilename);
It then finds the two occurrences of FF D8 (as 255 and 216):
beginBytes=strfind(bytes,char(255));
for i=1:length(beginBytes)
if bytes(beginBytes(i)+1)==char(216)
jpegCtr=jpegCtr+1;
offsets(jpegCtr)=beginBytes(i)
end
end
and tries to write out the first included jped:
fid=fopen('c:\stereophotomaker\childrens library_l.jpg','w');
% fprintf(fid,'%s',bytes(offsets(1):offsets(2))); % first tried way
%fwrite(fid,bytes(offsets(1):offsets(2)),'*char'); % second
fprintf(fid,'%s',bytes); %third
fclose('all');
but even when attempting a fraction of the original file, the newly created file is larger than the half file attempted, and the last trial produces a file larger than the whole original file, even though it's the same bytes.
Regardless of which method used, the resulting file is not recognized by Windows Media Player, though called a .jpg.
Respuesta aceptada
Les Beckham
el 28 de Jul. de 2023
fileread reads the file as text. You need to open the file and read it as binary bytes (uint8) and then process it that way.
Replace
bytes=fileread(infilename);
with
fp = fopen(infilename, 'r');
bytes = fread(fp, 'uint8')
and also replace your
beginBytes=strfind(bytes,char(255));
with
beginBytes = find(bytes == uint8(255));
and similarly for finding the 216 marker(s).
3 comentarios
Les Beckham
el 31 de Jul. de 2023
I'm glad that you got things figured out. Thanks for accepting my answer.
Más respuestas (1)
Image Analyst
el 29 de Jul. de 2023
See the FAQ for how to read in a series of files.
After you read them in, create an output file name that has PNG as the extension and call imwrite. Then it will write out the new image with exactly the same values it has in MATLAB. At this point, you'll have the same pixel values regardless if you read in the JPG version of the file or the PNG version of the file. Whatever you're going to do with the image matrices after that does not care what format the original disk files were in, so you might as well just stick with the JPG files (unless you plan on modifying the image matrix out and resaving it).
Ver también
Categorías
Más información sobre Environment and Settings en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!