fpreadbmp.pp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  1. {*****************************************************************************}
  2. {
  3. This file is part of the Free Pascal's "Free Components Library".
  4. Copyright (c) 2003 by Mazen NEIFER of the Free Pascal development team
  5. BMP reader implementation.
  6. See the file COPYING.FPC, included in this distribution,
  7. for details about the copyright.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  11. }
  12. {*****************************************************************************}
  13. { 08/2005 by Giulio Bernardi:
  14. - Added support for 16 and 15 bpp bitmaps.
  15. - If we have bpp <= 8 make an indexed image instead of converting it to RGB
  16. - Support for RLE4 and RLE8 decoding
  17. - Support for top-down bitmaps
  18. }
  19. {$mode objfpc}
  20. {$h+}
  21. unit FPReadBMP;
  22. interface
  23. uses FPImage, classes, sysutils, BMPcomn;
  24. type
  25. TFPReaderBMP = class (TFPCustomImageReader)
  26. Private
  27. DeltaX, DeltaY : integer; // Used for the never-used delta option in RLE
  28. TopDown : boolean; // If set, bitmap is stored top down instead of bottom up
  29. continue : boolean; // needed for onprogress event
  30. percent : byte;
  31. percentinterval : longword;
  32. percentacc : longword;
  33. Rect : TRect;
  34. Procedure FreeBufs; // Free (and nil) buffers.
  35. protected
  36. ReadSize : Integer; // Size (in bytes) of 1 scanline.
  37. BFI : TBitMapInfoHeader; // The header as read from the stream.
  38. FPalette : PFPcolor; // Buffer with Palette entries. (useless now)
  39. LineBuf : PByte; // Buffer for 1 scanline. Can be Byte, Word, TColorRGB or TColorRGBA
  40. RedMask, GreenMask, BlueMask : longword; //Used if Compression=bi_bitfields
  41. RedShift, GreenShift, BlueShift : shortint;
  42. // SetupRead will allocate the needed buffers, and read the colormap if needed.
  43. procedure SetupRead(nPalette, nRowBits: Integer; Stream : TStream); virtual;
  44. function CountBits(Value : byte) : shortint;
  45. function ShiftCount(Mask : longword) : shortint;
  46. function ExpandColor(value : longword) : TFPColor;
  47. procedure ExpandRLE8ScanLine(Row : Integer; Stream : TStream);
  48. procedure ExpandRLE4ScanLine(Row : Integer; Stream : TStream);
  49. procedure ReadScanLine(Row : Integer; Stream : TStream); virtual;
  50. procedure WriteScanLine(Row : Integer; Img : TFPCustomImage); virtual;
  51. // required by TFPCustomImageReader
  52. procedure InternalRead (Stream:TStream; Img:TFPCustomImage); override;
  53. function InternalCheck (Stream:TStream) : boolean; override;
  54. public
  55. constructor Create; override;
  56. destructor Destroy; override;
  57. property XPelsPerMeter : integer read BFI.XPelsPerMeter;
  58. property YPelsPerMeter : integer read BFI.YPelsPerMeter;
  59. end;
  60. implementation
  61. function RGBAToFPColor(Const RGBA: TColorRGBA) : TFPcolor;
  62. begin
  63. with Result, RGBA do
  64. begin
  65. Red :=(R shl 8) or R;
  66. Green :=(G shl 8) or G;
  67. Blue :=(B shl 8) or B;
  68. Alpha :=255-A;
  69. Alpha :=(Alpha shl 8) or Alpha
  70. end;
  71. end;
  72. Function RGBToFPColor(Const RGB : TColorRGB) : TFPColor;
  73. begin
  74. with Result,RGB do
  75. begin {Use only the high byte to convert the color}
  76. Red := (R shl 8) + R;
  77. Green := (G shl 8) + G;
  78. Blue := (B shl 8) + B;
  79. Alpha := AlphaOpaque;
  80. end;
  81. end;
  82. Constructor TFPReaderBMP.create;
  83. begin
  84. inherited create;
  85. end;
  86. Destructor TFPReaderBMP.Destroy;
  87. begin
  88. FreeBufs;
  89. inherited destroy;
  90. end;
  91. Procedure TFPReaderBMP.FreeBufs;
  92. begin
  93. If (LineBuf<>Nil) then
  94. begin
  95. FreeMem(LineBuf);
  96. LineBuf:=Nil;
  97. end;
  98. If (FPalette<>Nil) then
  99. begin
  100. FreeMem(FPalette);
  101. FPalette:=Nil;
  102. end;
  103. end;
  104. { Counts how many bits are set }
  105. function TFPReaderBMP.CountBits(Value : byte) : shortint;
  106. begin
  107. Result:=PopCnt(Value);
  108. end;
  109. { If compression is bi_bitfields, there could be arbitrary masks for colors.
  110. Although this is not compatible with windows9x it's better to know how to read these bitmaps
  111. We must determine how to switch the value once masked
  112. Example: 0000 0111 1110 0000, if we shr 5 we have 00XX XXXX for the color, but these bits must be the
  113. highest in the color, so we must shr (5-(8-6))=3, and we have XXXX XX00.
  114. A negative value means "shift left" }
  115. function TFPReaderBMP.ShiftCount(Mask : longword) : shortint;
  116. var tmp : shortint;
  117. begin
  118. tmp:=0;
  119. if Mask=0 then
  120. begin
  121. Result:=0;
  122. exit;
  123. end;
  124. while (Mask mod 2)=0 do { rightmost bit is 0 }
  125. begin
  126. inc(tmp);
  127. Mask:= Mask shr 1;
  128. end;
  129. tmp:=tmp-(8-popcnt(byte(Mask and $FF)));
  130. Result:=tmp;
  131. end;
  132. function TFPReaderBMP.ExpandColor(value : longword) : TFPColor;
  133. var tmpr, tmpg, tmpb : longword;
  134. col : TColorRGB;
  135. begin
  136. {$IFDEF ENDIAN_BIG}
  137. value:=swap(value);
  138. {$ENDIF}
  139. tmpr:=value and RedMask;
  140. tmpg:=value and GreenMask;
  141. tmpb:=value and BlueMask;
  142. if RedShift < 0 then col.R:=byte(tmpr shl (-RedShift))
  143. else col.R:=byte(tmpr shr RedShift);
  144. if GreenShift < 0 then col.G:=byte(tmpg shl (-GreenShift))
  145. else col.G:=byte(tmpg shr GreenShift);
  146. if BlueShift < 0 then col.B:=byte(tmpb shl (-BlueShift))
  147. else col.B:=byte(tmpb shr BlueShift);
  148. Result:=RGBToFPColor(col);
  149. end;
  150. procedure TFPReaderBMP.SetupRead(nPalette, nRowBits: Integer; Stream : TStream);
  151. var
  152. ColInfo: ARRAY OF TColorRGBA;
  153. i: Integer;
  154. begin
  155. if ((BFI.Compression=BI_RGB) and (BFI.BitCount=16)) then { 5 bits per channel, fixed mask }
  156. begin
  157. RedMask:=$7C00; RedShift:=7;
  158. GreenMask:=$03E0; GreenShift:=2;
  159. BlueMask:=$001F; BlueShift:=-3;
  160. end
  161. else if ((BFI.Compression=BI_BITFIELDS) and (BFI.BitCount in [16,32])) then { arbitrary mask }
  162. begin
  163. Stream.Read(RedMask,4);
  164. Stream.Read(GreenMask,4);
  165. Stream.Read(BlueMask,4);
  166. {$IFDEF ENDIAN_BIG}
  167. RedMask:=swap(RedMask);
  168. GreenMask:=swap(GreenMask);
  169. BlueMask:=swap(BlueMask);
  170. {$ENDIF}
  171. RedShift:=ShiftCount(RedMask);
  172. GreenShift:=ShiftCount(GreenMask);
  173. BlueShift:=ShiftCount(BlueMask);
  174. end
  175. else if nPalette>0 then
  176. begin
  177. GetMem(FPalette, nPalette*SizeOf(TFPColor));
  178. SetLength(ColInfo, nPalette);
  179. if BFI.ClrUsed>0 then
  180. Stream.Read(ColInfo[0],BFI.ClrUsed*SizeOf(TColorRGBA))
  181. else // Seems to me that this is dangerous.
  182. Stream.Read(ColInfo[0],nPalette*SizeOf(TColorRGBA));
  183. for i := 0 to High(ColInfo) do
  184. FPalette[i] := RGBAToFPColor(ColInfo[i]);
  185. end
  186. else if BFI.ClrUsed>0 then { Skip palette }
  187. Stream.Position := Stream.Position + BFI.ClrUsed*SizeOf(TColorRGBA);
  188. ReadSize:=((nRowBits + 31) div 32) shl 2;
  189. GetMem(LineBuf,ReadSize);
  190. end;
  191. procedure TFPReaderBMP.InternalRead(Stream:TStream; Img:TFPCustomImage);
  192. // NOTE: Assumes that BMP header already has been read
  193. Var
  194. Row, i, pallen : Integer;
  195. BadCompression : boolean;
  196. begin
  197. Rect.Left:=0; Rect.Top:=0; Rect.Right:=0; Rect.Bottom:=0;
  198. continue:=true;
  199. Progress(psStarting,0,false,Rect,'',continue);
  200. if not continue then exit;
  201. Stream.Read(BFI,SizeOf(BFI));
  202. {$IFDEF ENDIAN_BIG}
  203. SwapBMPInfoHeader(BFI);
  204. {$ENDIF}
  205. { This will move past any junk after the BFI header }
  206. Stream.Position:=Stream.Position-SizeOf(BFI)+BFI.Size;
  207. with BFI do
  208. begin
  209. BadCompression:=false;
  210. if ((Compression=BI_RLE4) and (BitCount<>4)) then BadCompression:=true;
  211. if ((Compression=BI_RLE8) and (BitCount<>8)) then BadCompression:=true;
  212. if ((Compression=BI_BITFIELDS) and (not (BitCount in [16,32]))) then BadCompression:=true;
  213. if not (Compression in [BI_RGB..BI_BITFIELDS]) then BadCompression:=true;
  214. if BadCompression then
  215. raise FPImageException.Create('Bad BMP compression mode');
  216. TopDown:=(Height<0);
  217. Height:=abs(Height);
  218. if (TopDown and (not (Compression in [BI_RGB,BI_BITFIELDS]))) then
  219. raise FPImageException.Create('Top-down bitmaps cannot be compressed');
  220. Img.SetSize(0,0);
  221. if BitCount<=8 then
  222. begin
  223. Img.UsePalette:=true;
  224. Img.Palette.Clear;
  225. end
  226. else Img.UsePalette:=false;
  227. Case BFI.BitCount of
  228. 1 : { Monochrome }
  229. SetupRead(2,Width,Stream);
  230. 4 :
  231. SetupRead(16,Width*4,Stream);
  232. 8 :
  233. SetupRead(256,Width*8,Stream);
  234. 16 :
  235. SetupRead(0,Width*8*2,Stream);
  236. 24:
  237. SetupRead(0,Width*8*3,Stream);
  238. 32:
  239. SetupRead(0,Width*8*4,Stream);
  240. end;
  241. end;
  242. Try
  243. { Note: it would be better to Fill the image palette in setupread instead of creating FPalette.
  244. FPalette is indeed useless but we cannot remove it since it's not private :\ }
  245. pallen:=0;
  246. if BFI.BitCount<=8 then
  247. if BFI.ClrUsed>0 then pallen:=BFI.ClrUsed
  248. else pallen:=(1 shl BFI.BitCount);
  249. if pallen>0 then
  250. begin
  251. Img.Palette.Count:=pallen;
  252. for i:=0 to pallen-1 do
  253. Img.Palette.Color[i]:=FPalette[i];
  254. end;
  255. Img.SetSize(BFI.Width,BFI.Height);
  256. percent:=0;
  257. percentinterval:=(Img.Height*4) div 100;
  258. if percentinterval=0 then percentinterval:=$FFFFFFFF;
  259. percentacc:=0;
  260. DeltaX:=-1; DeltaY:=-1;
  261. if TopDown then
  262. for Row:=0 to Img.Height-1 do { A rare case of top-down bitmap! }
  263. begin
  264. ReadScanLine(Row,Stream); // Scanline in LineBuf with Size ReadSize.
  265. WriteScanLine(Row,Img);
  266. if not continue then exit;
  267. end
  268. else
  269. for Row:=Img.Height-1 downto 0 do
  270. begin
  271. ReadScanLine(Row,Stream); // Scanline in LineBuf with Size ReadSize.
  272. WriteScanLine(Row,Img);
  273. if not continue then exit;
  274. end;
  275. Progress(psEnding,100,false,Rect,'',continue);
  276. finally
  277. FreeBufs;
  278. end;
  279. end;
  280. procedure TFPReaderBMP.ExpandRLE8ScanLine(Row : Integer; Stream : TStream);
  281. var i,j : integer;
  282. b0, b1 : byte;
  283. begin
  284. i:=0;
  285. while true do
  286. begin
  287. { let's see if we must skip pixels because of delta... }
  288. if DeltaY<>-1 then
  289. begin
  290. if Row=DeltaY then j:=DeltaX { If we are on the same line, skip till DeltaX }
  291. else j:=ReadSize; { else skip up to the end of this line }
  292. while (i<j) do
  293. begin
  294. LineBuf[i]:=0;
  295. inc(i);
  296. end;
  297. if Row=DeltaY then { we don't need delta anymore }
  298. DeltaY:=-1
  299. else break; { skipping must continue on the next line, we are finished here }
  300. end;
  301. Stream.Read(b0,1); Stream.Read(b1,1);
  302. if b0<>0 then { number of repetitions }
  303. begin
  304. if b0+i>ReadSize then
  305. raise FPImageException.Create('Bad BMP RLE chunk at row '+inttostr(row)+', col '+inttostr(i)+', file offset $'+inttohex(Stream.Position,16) );
  306. j:=i+b0;
  307. while (i<j) do
  308. begin
  309. LineBuf[i]:=b1;
  310. inc(i);
  311. end;
  312. end
  313. else
  314. case b1 of
  315. 0: break; { end of line }
  316. 1: break; { end of file }
  317. 2: begin { Next pixel position. Skipped pixels should be left untouched, but we set them to zero }
  318. Stream.Read(b0,1); Stream.Read(b1,1);
  319. DeltaX:=i+b0; DeltaY:=Row+b1;
  320. end
  321. else begin { absolute mode }
  322. if b1+i>ReadSize then
  323. raise FPImageException.Create('Bad BMP RLE chunk at row '+inttostr(row)+', col '+inttostr(i)+', file offset $'+inttohex(Stream.Position,16) );
  324. Stream.Read(LineBuf[i],b1);
  325. inc(i,b1);
  326. { aligned on 2 bytes boundary: every group starts on a 2 bytes boundary, but absolute group
  327. could end on odd address if there is a odd number of elements, so we pad it }
  328. if (b1 mod 2)<>0 then Stream.Seek(1,soFromCurrent);
  329. end;
  330. end;
  331. end;
  332. end;
  333. procedure TFPReaderBMP.ExpandRLE4ScanLine(Row : Integer; Stream : TStream);
  334. var i,j,tmpsize : integer;
  335. b0, b1 : byte;
  336. nibline : pbyte; { temporary array of nibbles }
  337. even : boolean;
  338. begin
  339. tmpsize:=ReadSize*2; { ReadSize is in bytes, while nibline is made of nibbles, so it's 2*readsize long }
  340. getmem(nibline,tmpsize);
  341. if nibline=nil then
  342. raise FPImageException.Create('Out of memory');
  343. try
  344. i:=0;
  345. while true do
  346. begin
  347. { let's see if we must skip pixels because of delta... }
  348. if DeltaY<>-1 then
  349. begin
  350. if Row=DeltaY then j:=DeltaX { If we are on the same line, skip till DeltaX }
  351. else j:=tmpsize; { else skip up to the end of this line }
  352. while (i<j) do
  353. begin
  354. NibLine[i]:=0;
  355. inc(i);
  356. end;
  357. if Row=DeltaY then { we don't need delta anymore }
  358. DeltaY:=-1
  359. else break; { skipping must continue on the next line, we are finished here }
  360. end;
  361. Stream.Read(b0,1); Stream.Read(b1,1);
  362. if b0<>0 then { number of repetitions }
  363. begin
  364. if b0+i>tmpsize then
  365. raise FPImageException.Create('Bad BMP RLE chunk at row '+inttostr(row)+', col '+inttostr(i)+', file offset $'+inttohex(Stream.Position,16) );
  366. even:=true;
  367. j:=i+b0;
  368. while (i<j) do
  369. begin
  370. if even then NibLine[i]:=(b1 and $F0) shr 4
  371. else NibLine[i]:=b1 and $0F;
  372. inc(i);
  373. even:=not even;
  374. end;
  375. end
  376. else
  377. case b1 of
  378. 0: break; { end of line }
  379. 1: break; { end of file }
  380. 2: begin { Next pixel position. Skipped pixels should be left untouched, but we set them to zero }
  381. Stream.Read(b0,1); Stream.Read(b1,1);
  382. DeltaX:=i+b0; DeltaY:=Row+b1;
  383. end
  384. else begin { absolute mode }
  385. if b1+i>tmpsize then
  386. raise FPImageException.Create('Bad BMP RLE chunk at row '+inttostr(row)+', col '+inttostr(i)+', file offset $'+inttohex(Stream.Position,16) );
  387. j:=i+b1;
  388. even:=true;
  389. while (i<j) do
  390. begin
  391. if even then
  392. begin
  393. Stream.Read(b0,1);
  394. NibLine[i]:=(b0 and $F0) shr 4;
  395. end
  396. else NibLine[i]:=b0 and $0F;
  397. inc(i);
  398. even:=not even;
  399. end;
  400. { aligned on 2 bytes boundary: see rle8 for details }
  401. b1:=b1+(b1 mod 2);
  402. if (b1 mod 4)<>0 then Stream.Seek(1,soFromCurrent);
  403. end;
  404. end;
  405. end;
  406. { pack the nibline into the linebuf }
  407. for i:=0 to ReadSize-1 do
  408. LineBuf[i]:=(NibLine[i*2] shl 4) or NibLine[i*2+1];
  409. finally
  410. FreeMem(nibline)
  411. end;
  412. end;
  413. procedure TFPReaderBMP.ReadScanLine(Row : Integer; Stream : TStream);
  414. begin
  415. if BFI.Compression=BI_RLE8 then ExpandRLE8ScanLine(Row,Stream)
  416. else if BFI.Compression=BI_RLE4 then ExpandRLE4ScanLine(Row,Stream)
  417. else Stream.Read(LineBuf[0],ReadSize);
  418. end;
  419. procedure TFPReaderBMP.WriteScanLine(Row : Integer; Img : TFPCustomImage);
  420. Var
  421. Column : Integer;
  422. begin
  423. Case BFI.BitCount of
  424. 1 :
  425. for Column:=0 to Img.Width-1 do
  426. if ((LineBuf[Column div 8] shr (7-(Column and 7)) ) and 1) <> 0 then
  427. img.Pixels[Column,Row]:=1
  428. else
  429. img.Pixels[Column,Row]:=0;
  430. 4 :
  431. for Column:=0 to img.Width-1 do
  432. img.Pixels[Column,Row]:=(LineBuf[Column div 2] shr (((Column+1) and 1)*4)) and $0f;
  433. 8 :
  434. for Column:=0 to img.Width-1 do
  435. img.Pixels[Column,Row]:=LineBuf[Column];
  436. 16 :
  437. for Column:=0 to img.Width-1 do
  438. img.colors[Column,Row]:=ExpandColor(PWord(LineBuf)[Column]);
  439. 24 :
  440. for Column:=0 to img.Width-1 do
  441. img.colors[Column,Row]:=RGBToFPColor(PColorRGB(LineBuf)[Column]);
  442. 32 :
  443. for Column:=0 to img.Width-1 do
  444. if BFI.Compression=BI_BITFIELDS then
  445. img.colors[Column,Row]:=ExpandColor(PLongWord(LineBuf)[Column])
  446. else
  447. img.colors[Column,Row]:=RGBAToFPColor(PColorRGBA(LineBuf)[Column]);
  448. end;
  449. inc(percentacc,4);
  450. if percentacc>=percentinterval then
  451. begin
  452. percent:=percent+(percentacc div percentinterval);
  453. percentacc:=percentacc mod percentinterval;
  454. Progress(psRunning,percent,false,Rect,'',continue);
  455. end;
  456. end;
  457. function TFPReaderBMP.InternalCheck (Stream:TStream) : boolean;
  458. // NOTE: Does not rewind the stream!
  459. var
  460. BFH:TBitMapFileHeader;
  461. n: Int64;
  462. begin
  463. Result:=False;
  464. if Stream=nil then
  465. exit;
  466. n:=SizeOf(BFH);
  467. Result:=Stream.Read(BFH,n)=n;
  468. if Result then
  469. begin
  470. {$IFDEF ENDIAN_BIG}
  471. SwapBMPFileHeader(BFH);
  472. {$ENDIF}
  473. Result := BFH.bfType = BMmagic; // Just check magic number
  474. end;
  475. end;
  476. initialization
  477. ImageHandlers.RegisterImageReader ('BMP Format', 'bmp', TFPReaderBMP);
  478. end.