ksBitmapHelper.pas 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850
  1. unit ksBitmapHelper;
  2. // 部分拷贝自 FlyUtils.TBitmapHelper
  3. {$DEFINE FMX}
  4. interface
  5. uses
  6. {$IFDEF FMX}
  7. FMX.Graphics,
  8. FMX.Utils,
  9. FMX.Types,
  10. FMX.Surfaces,
  11. {$ELSE}
  12. Vcl.Graphics,
  13. {$ENDIF}
  14. System.Types,
  15. System.UITypes,
  16. System.Classes;
  17. {$IFDEF FMX}
  18. {$ELSE}
  19. resourcestring
  20. SBitmapSavingFailed = 'Saving bitmap failed.';
  21. SBitmapSavingFailedNamed = 'Saving bitmap failed (%s).';
  22. {$ENDIF}
  23. var
  24. MonochromeChange_Threshold: Byte = 120;
  25. MonochromeChange_Weighting_Red: Double = 0.3;
  26. MonochromeChange_Weighting_Green: Double = 0.59;
  27. MonochromeChange_Weighting_Blue: Double = 0.11;
  28. type
  29. /// <summary>
  30. /// 转黑白的方法
  31. /// </summary>
  32. TMonochromeChangeType = (
  33. /// <summary>
  34. /// 平均值
  35. /// </summary>
  36. Average,
  37. /// <summary>
  38. /// 权值
  39. /// </summary>
  40. Weighting,
  41. /// <summary>
  42. /// 最大值
  43. /// </summary>
  44. Max);
  45. /// <summary>
  46. /// <para>
  47. /// TBitmap Save As BMP
  48. /// </para>
  49. /// <para>
  50. /// BytesPerPixel = -1 表示自动
  51. /// </para>
  52. /// </summary>
  53. TKngStrBitmapHelper = class helper for TBitmap
  54. public
  55. function SaveAsBMPToFile(const AFileName: string; const BytesPerPixel: Integer = 3;
  56. const MonochromeChangeType: TMonochromeChangeType = TMonochromeChangeType.Average): Boolean; overload;
  57. procedure SaveAsBMPToFileDef(const AFileName: string); overload;
  58. function SaveAsBMPToStream(const AStream: TStream; const BytesPerPixel: Integer = 3;
  59. const MonochromeChangeType: TMonochromeChangeType = TMonochromeChangeType.Average): Boolean; overload;
  60. procedure SaveAsBMPToStreamDef(Stream: TStream); overload;
  61. {$IFDEF FMX}
  62. /// <summary>
  63. /// 用于在线程中代替 LoadFromFile ,不用自己调用 Synchronize 了。
  64. /// </summary>
  65. procedure SyncLoadFromFile(const AFileName: string);
  66. /// <summary>
  67. /// 用于在线程中代替 LoadThumbnailFromFile ,不用自己调用 Synchronize 了。
  68. /// </summary>
  69. /// <remarks>
  70. /// UseEmbedded 只有Windows下可用,而且缩略图大小不可控
  71. /// </remarks>
  72. procedure SyncLoadThumbnailFromFile(const AFileName: string; const AFitWidth, AFitHeight: Single;
  73. const UseEmbedded: Boolean = True);
  74. /// <summary>
  75. /// 用于在线程中代替 LoadFromStream ,不用自己调用 Synchronize 了。
  76. /// </summary>
  77. procedure SyncLoadFromStream(Stream: TStream);
  78. /// <summary>
  79. /// 用于在线程中代替 LoadThumbnailFromStream ,不用自己调用 Synchronize 了。
  80. /// </summary>
  81. /// <remarks>
  82. /// UseEmbedded 只有Windows下可用,而且缩略图大小不可控
  83. /// </remarks>
  84. procedure SyncLoadThumbnailFromStream(const Stream: TStream; const AFitWidth, AFitHeight: Single;
  85. const UseEmbedded: Boolean = True; const AutoCut: Boolean = True); overload;
  86. function SyncLoadThumbnailFromStream(const AStream: TStream; const ASrc, ADest: TRectF;
  87. const UseEmbedded: Boolean): Boolean; overload;
  88. /// <summary>
  89. /// 用于在线程中代替 Assign ,不用自己调用 Synchronize 了。
  90. /// </summary>
  91. procedure SyncAssign(Source: TPersistent);
  92. {$ENDIF}
  93. end;
  94. {$IFDEF FMX}
  95. TBitmapCodecDescriptorField = (Extension, Description);
  96. TKngStrBitmapCodecManager = class helper for TBitmapCodecManager
  97. strict private
  98. class function GuessCodecClass(const Name: string; const Field: TBitmapCodecDescriptorField): TCustomBitmapCodecClass;
  99. public
  100. class function GetImageSize(const AFileName: string): TPointF; overload;
  101. class function GetImageSize(const AStream: TStream): TPointF; overload;
  102. class function LoadFromStream(const AStream: TStream; const Bitmap: TBitmapSurface;
  103. const MaxSizeLimit: Cardinal = 0): Boolean;
  104. /// <remarks>
  105. /// UseEmbedded 只有Windows下可用,而且缩略图大小不可控
  106. /// </remarks>
  107. class function LoadThumbnailFromStream(const AStream: TStream; const AFitWidth, AFitHeight: Single;
  108. const UseEmbedded: Boolean; const AutoCut: Boolean; const Bitmap: TBitmapSurface): Boolean; overload;
  109. /// <remarks>
  110. /// UseEmbedded 只有Windows下可用,而且缩略图大小不可控
  111. /// </remarks>
  112. class function LoadThumbnailFromStream(const AStream: TStream; const ASrc, ADest: TRectF;
  113. const UseEmbedded: Boolean; const Bitmap: TBitmapSurface): Boolean; overload;
  114. end;
  115. {$ENDIF}
  116. {$IFDEF FMX}
  117. {$ELSE}
  118. procedure GraphicToBitmap(const Src: Vcl.Graphics.TGraphic;
  119. const Dest: Vcl.Graphics.TBitmap; const TransparentColor: Vcl.Graphics.TColor = Vcl.Graphics.clNone);
  120. {$ENDIF}
  121. const
  122. SizeOftagBITMAPFILEHEADER = 14;
  123. SizeOftagBITMAPINFOHEADER = 40;
  124. RGB565ExtDataLen = 12;
  125. {$IFDEF FMX}
  126. function FillScanLineFormMemory(BitmapData: TBitmapData; ScanLineIndex, Width: integer;
  127. InputData: Pointer; InputFormat: TPixelFormat): Boolean;
  128. type
  129. // copy form [广州]庾伟洪<ywthegod@qq.com>
  130. TBitmap16bitFiler = class
  131. class var
  132. Color: array [0 .. $FFFF] of TAlphaColor;
  133. class constructor Create;
  134. class procedure FillScanLine(D: TBitmapData; ScanLine, Width: integer;
  135. data: Pointer); inline;
  136. end;
  137. // PAlphaColorArray = ^TAlphaColorArray; //FMX.Utils,
  138. // TWordArray = array [0 .. 0] of Word;
  139. // PWordArray = ^TWordArray; //System.SysUtils
  140. // y 行号 h 高度 w 宽度 b 一个像素用字节数
  141. // FVideoBuf 数据内存
  142. // bm.Map(TMapAccess.Write, bd);
  143. // try
  144. // for y := 0 to h - 1 do
  145. // begin
  146. // TBitmap16bitFiler.FillScanLine(bd, y, w, Addr(FVideoBuf[y * w * b]));
  147. // end;
  148. // finally
  149. // bm.Unmap(bd);
  150. // end;
  151. {$ENDIF}
  152. implementation
  153. uses
  154. {$IFDEF FMX}
  155. FMX.Consts,
  156. {$IFDEF ANDROID}
  157. FMX.Graphics.Android,
  158. Androidapi.JNIBridge,
  159. Androidapi.Helpers,
  160. FMX.Helpers.Android,
  161. Androidapi.JNI.GraphicsContentViewText,
  162. {$ENDIF}
  163. {$IFDEF MSWINDOWS}
  164. FMX.Canvas.D2D, Winapi.Wincodec, Winapi.Windows,
  165. {$ENDIF}
  166. {$ELSE}
  167. Vcl.Consts,
  168. {$ENDIF}
  169. System.SysConst,
  170. System.SysUtils,
  171. System.Math;
  172. //add by 爱吃猪头肉。
  173. type
  174. //感谢 yu 273637089 的测试和 提供 packed 信息。
  175. {$IFDEF FMX}
  176. {$ELSE}
  177. tagRGBTRIPLE = packed record
  178. rgbtBlue: Byte;
  179. rgbtGreen: Byte;
  180. rgbtRed: Byte;
  181. end;
  182. PRGBTripleArray = ^TRGBTripleArray;
  183. TRGBTripleArray = array [Byte] of tagRGBTRIPLE;
  184. {$ENDIF}
  185. tagBITMAPFILEHEADER = packed record
  186. bfType: Word;
  187. bfSize: DWORD;
  188. bfReserved1: Word;
  189. bfReserved2: Word;
  190. bfOffBits: DWORD;
  191. end;
  192. tagBITMAPINFOHEADER = packed record
  193. biSize: DWORD;
  194. biWidth: Longint;
  195. biHeight: Longint;
  196. biPlanes: Word;
  197. biBitCount: Word;
  198. biCompression: DWORD;
  199. biSizeImage: DWORD;
  200. biXPelsPerMeter: Longint;
  201. biYPelsPerMeter: Longint;
  202. biClrUsed: DWORD;
  203. biClrImportant: DWORD;
  204. end;
  205. tagRGBQUAD = packed record
  206. rgbBlue: Byte;
  207. rgbGreen: Byte;
  208. rgbRed: Byte;
  209. rgbReserved: Byte;
  210. end;
  211. {$IFDEF FMX}
  212. {$IFDEF ANDROID}
  213. TBitmapCodecAndroid = class(FMX.Graphics.Android.TBitmapCodecAndroid)
  214. private
  215. class function IsGIFStream(const Stream: TStream): Boolean;
  216. function LoadMovieFromStreamScaled(const AStream: TStream;
  217. const Surface: TBitmapSurface; const FitSize: TPoint): Boolean;
  218. function LoadMovieFromStream(const Stream: TStream;
  219. const Surface: TBitmapSurface): Boolean;
  220. function StretchIfNeed(const SrcBitmap: JBitmap;
  221. const Bitmap: TBitmapSurface; const LoadOptions: JBitmapFactory_Options;
  222. const MaxSizeLimit: Cardinal): Boolean;
  223. class function GetMovieSize(const Stream: TStream): TPoint;
  224. public
  225. class function GetImageSize(const AFileName: string): TPointF; overload;
  226. class function GetImageSize(const AStream: TStream): TPointF; overload;
  227. function LoadFromStream(const AStream: TStream; const Bitmap: TBitmapSurface;
  228. const MaxSizeLimit: Cardinal): Boolean; override;
  229. function LoadThumbnailFromStream(const AStream: TStream; const AFitWidth, AFitHeight: Single;
  230. const UseEmbedded: Boolean; const AutoCut: Boolean; const Bitmap: TBitmapSurface): Boolean; overload;
  231. function LoadThumbnailFromStream(const AStream: TStream; const ASrc, ADest: TRectF;
  232. const UseEmbedded: Boolean; const Bitmap: TBitmapSurface): Boolean; overload;
  233. end;
  234. {$ENDIF}
  235. {$IFDEF MSWINDOWS}
  236. TBitmapCodecWIC = class(FMX.Canvas.D2D.TCustomBitmapCodecWIC)
  237. private
  238. function DecodeFrame(const Frame: IWICBitmapFrameDecode; const Bitmap: TBitmapSurface;
  239. const MaxSizeLimit: Cardinal = 0): Boolean;
  240. public
  241. class function GetImageSize(const AStream: TStream): TPointF; overload;
  242. function LoadThumbnailFromStream(const AStream: TStream; const AFitWidth, AFitHeight: Single;
  243. const UseEmbedded: Boolean; const AutoCut: Boolean; const Bitmap: TBitmapSurface): Boolean; overload;
  244. function LoadThumbnailFromStream(const AStream: TStream; const ASrc, ADest: TRectF;
  245. const UseEmbedded: Boolean; const Bitmap: TBitmapSurface): Boolean; overload;
  246. end;
  247. {$ENDIF}
  248. {$ENDIF}
  249. const
  250. { constants for the biCompression field }
  251. {$EXTERNALSYM BI_RGB}
  252. BI_RGB = 0;
  253. {$EXTERNALSYM BI_RLE8}
  254. BI_RLE8 = 1;
  255. {$EXTERNALSYM BI_RLE4}
  256. BI_RLE4 = 2;
  257. {$EXTERNALSYM BI_BITFIELDS}
  258. BI_BITFIELDS = 3;
  259. const
  260. RGB565_MASK_RED = $F800;
  261. RGB565_MASK_GREEN = $07E0;
  262. RGB565_MASK_BLUE = $001F;
  263. // RGB565ExtDataLen = 12;
  264. function rgb_24_2_565(r,g,b: Byte): UInt16;
  265. begin
  266. // r := r * 31 div 255;
  267. // g := g * 64 div 255;
  268. // b := b * 31 div 255;
  269. // Result := r *2048 or g *32 or b;
  270. // Result := ((r shl 8) and RGB565_MASK_RED) or ((g shl 3) and RGB565_MASK_GREEN) or (b shr 3);
  271. Result := ((r shr 3) shl 11) or ((g shr 2 ) shl 5) or (b shr 3);
  272. end;
  273. {
  274. return (USHORT)(((unsigned(r) << 8) & 0xF800) |
  275. ((unsigned(g) << 3) & 0x7E0) |
  276. ((unsigned(b) >> 3)));
  277. }
  278. procedure rgb565_2_rgb24(rgb24: TBytes; rgb565: UInt16);
  279. begin
  280. //extract RGB
  281. rgb24[2] := (rgb565 and RGB565_MASK_RED) shr 11;
  282. rgb24[1] := (rgb565 and RGB565_MASK_GREEN) shr 5;
  283. rgb24[0] := (rgb565 and RGB565_MASK_BLUE);
  284. //amplify the image
  285. rgb24[2] := rgb24[2] shl 3;
  286. rgb24[1] := rgb24[2] shl 2;
  287. rgb24[0] := rgb24[2] shl 3;
  288. end;
  289. {
  290. //extract RGB
  291. rgb24[2] = (rgb565 & RGB565_MASK_RED) >> 11;
  292. rgb24[1] = (rgb565 & RGB565_MASK_GREEN) >> 5;
  293. rgb24[0] = (rgb565 & RGB565_MASK_BLUE);
  294. //amplify the image
  295. rgb24[2] <<= 3;
  296. rgb24[1] <<= 2;
  297. rgb24[0] <<= 3;
  298. }
  299. const
  300. RGB555_MASK_RED = $7C00;
  301. RGB555_MASK_GREEN = $03E0;
  302. RGB555_MASK_BLUE = $001F;
  303. function rgb_24_2_555(r,g,b: Byte): UInt16;
  304. begin
  305. Result := ((r shl 7) and RGB555_MASK_RED) or ((g shl 2) and RGB555_MASK_GREEN) or (b shr 3);
  306. end;
  307. procedure rgb555_2_rgb24(rgb24: TBytes; rgb555: UInt16);
  308. begin
  309. //extract RGB
  310. rgb24[0] := (rgb555 shl 3) and $00F8;
  311. rgb24[1] := (rgb555 shr 2) and $00F8;
  312. rgb24[2] := (rgb555 shr 7) and $00F8;
  313. end;
  314. {$IFDEF FMX}
  315. {$ELSE}
  316. procedure GraphicToBitmap(const Src: Vcl.Graphics.TGraphic;
  317. const Dest: Vcl.Graphics.TBitmap; const TransparentColor: Vcl.Graphics.TColor = Vcl.Graphics.clNone);
  318. begin
  319. // Do nothing if either source or destination are nil
  320. if not Assigned(Src) or not Assigned(Dest) then
  321. Exit;
  322. if Src.Empty then exit;
  323. // Size the bitmap
  324. Dest.Width := Src.Width;
  325. Dest.Height := Src.Height;
  326. if Src.Transparent then
  327. begin
  328. // Source graphic is transparent, make bitmap behave transparently
  329. Dest.Transparent := True;
  330. if (TransparentColor <> Vcl.Graphics.clNone) then
  331. begin
  332. // Set destination as transparent using required colour key
  333. Dest.TransparentColor := TransparentColor;
  334. Dest.TransparentMode := Vcl.Graphics.tmFixed;
  335. // Set background colour of bitmap to transparent colour
  336. Dest.Canvas.Brush.Color := TransparentColor;
  337. end
  338. else
  339. // No transparent colour: set transparency to automatic
  340. Dest.TransparentMode := Vcl.Graphics.tmAuto;
  341. end;
  342. // Clear bitmap to required background colour and draw bitmap
  343. Dest.Canvas.FillRect(System.Classes.Rect(0, 0, Dest.Width, Dest.Height));
  344. Dest.Canvas.Draw(0, 0, Src);
  345. end;
  346. {$ENDIF}
  347. //该代码片段来自于: http://www.sharejs.com/codes/delphi/2248
  348. { TKngStrBitmapHelper }
  349. function TKngStrBitmapHelper.SaveAsBMPToFile(const AFileName: string; const BytesPerPixel: Integer = 3;
  350. const MonochromeChangeType: TMonochromeChangeType = TMonochromeChangeType.Average): Boolean;
  351. var
  352. AStream: TStream;
  353. begin
  354. Result := False;
  355. {$IFDEF FMX}
  356. if IsEmpty then exit;
  357. {$ELSE}
  358. if Empty then exit;
  359. {$ENDIF}
  360. AStream := TFileStream.Create(AFileName, fmCreate);// or fmOpenReadWrite);
  361. try
  362. Result := SaveAsBMPToStream(AStream, BytesPerPixel);
  363. // if Result then
  364. // AStream.Size := AStream.Position;
  365. finally
  366. FreeAndNil(AStream);
  367. end;
  368. end;
  369. procedure TKngStrBitmapHelper.SaveAsBMPToFileDef(const AFileName: string);
  370. begin
  371. if not SaveAsBMPToFile(AFileName) then
  372. begin
  373. {$IFDEF FMX}
  374. raise EBitmapSavingFailed.CreateFMT(SBitmapSavingFailed, [AFileName]);
  375. {$ELSE}
  376. raise EInvalidGraphicOperation.CreateFmt(SBitmapSavingFailed, [AFileName]);
  377. {$ENDIF}
  378. end;
  379. end;
  380. //http://blog.csdn.net/pjpsmile/article/details/8985523
  381. function TKngStrBitmapHelper.SaveAsBMPToStream(const AStream: TStream; const BytesPerPixel: Integer = 3;
  382. const MonochromeChangeType: TMonochromeChangeType = TMonochromeChangeType.Average): Boolean;
  383. var
  384. I, CurrBytesPerPixel,
  385. wWidth, nCol, wRow, wByteIdex,
  386. bfReserved1, bfReserved2,
  387. nBmpWidth, nBmpHeight, bufferSize: Integer;
  388. BitmapInfo: tagBITMAPINFOHEADER;
  389. BMF: tagBITMAPFILEHEADER;
  390. {$IFDEF FMX}
  391. Data: TBitmapData;
  392. clr: TAlphaColor;
  393. AlphaColorBuffer: PAlphaColor;
  394. {$ELSE}
  395. Pixs : pRGBTripleArray;
  396. {$ENDIF}
  397. bmpData: TBytes;
  398. A32BitData: UInt32;
  399. ABitIndex,
  400. A8BitData: Byte;
  401. RGBQUAD: tagRGBQUAD;
  402. // FileSizeFix,
  403. A16BitData,
  404. GrayeData: UInt16;
  405. begin
  406. Result := False;
  407. {$IFDEF FMX}
  408. if IsEmpty then exit;
  409. {$ELSE}
  410. if Empty then exit;
  411. {$ENDIF}
  412. if not Assigned(AStream) then exit;
  413. CurrBytesPerPixel := BytesPerPixel;
  414. {$IFDEF FMX}
  415. Map(TMapAccess.Read, Data);
  416. {$ELSE}
  417. {$ENDIF}
  418. try
  419. if CurrBytesPerPixel = -1 then
  420. begin
  421. {$IFDEF FMX}
  422. CurrBytesPerPixel := Data.BytesPerPixel;
  423. {$ELSE}
  424. CurrBytesPerPixel := 3;
  425. if PixelFormat = pf1bit then
  426. CurrBytesPerPixel := 0;
  427. if PixelFormat = pf4bit then
  428. CurrBytesPerPixel := 2;
  429. if PixelFormat = pf8bit then
  430. CurrBytesPerPixel := 2;
  431. if PixelFormat = pf15bit then
  432. CurrBytesPerPixel := 2;
  433. if PixelFormat = pf16bit then
  434. CurrBytesPerPixel := 2;
  435. if PixelFormat = pf24bit then
  436. CurrBytesPerPixel := 3;
  437. if PixelFormat = pf32bit then
  438. CurrBytesPerPixel := 4;
  439. {$ENDIF}
  440. if not (CurrBytesPerPixel in [0,1,2,4]) then
  441. CurrBytesPerPixel := 3;
  442. end;
  443. if not (CurrBytesPerPixel in [0,1,2,3,4]) then
  444. exit;
  445. //不打算支持 8 位的。
  446. if CurrBytesPerPixel = 1 then exit;
  447. {$IFDEF FMX}
  448. nBmpWidth := Data.Width;
  449. nBmpHeight := Data.Height;
  450. {$ELSE}
  451. nBmpWidth := Width;
  452. nBmpHeight := Height;
  453. {$ENDIF}
  454. // 像素扫描
  455. if CurrBytesPerPixel > 0 then
  456. begin
  457. wWidth := nBmpWidth * CurrBytesPerPixel;
  458. if (wWidth mod 4) > 0 then
  459. begin
  460. wWidth := wWidth + 4 - (wWidth mod 4);
  461. end;
  462. end
  463. else if (nBmpWidth mod 32) > 0 then
  464. begin
  465. wWidth := ((nBmpWidth div 32) + 1) * 4;;
  466. end
  467. else
  468. begin
  469. wWidth := (nBmpWidth div 8);
  470. end;
  471. bufferSize := nBmpHeight * wWidth;
  472. // bmp文件头
  473. BMF.bfType := $4D42;
  474. BMF.bfSize := 14 + 40 + bufferSize;
  475. BMF.bfReserved1 := 0;
  476. BMF.bfReserved2 := 0;
  477. BMF.bfOffBits := 14 + 40;
  478. if (CurrBytesPerPixel = 0) then
  479. begin
  480. BMF.bfOffBits := BMF.bfOffBits + 2 * Sizeof(RGBQUAD);
  481. BMF.bfSize := BMF.bfSize + 2 * Sizeof(RGBQUAD);
  482. end;
  483. if (CurrBytesPerPixel = 1) then
  484. begin
  485. BMF.bfOffBits := BMF.bfOffBits + 256 * Sizeof(RGBQUAD);
  486. BMF.bfSize := BMF.bfSize + 256 * Sizeof(RGBQUAD);
  487. end;
  488. if (CurrBytesPerPixel = 2) then
  489. begin
  490. //多谢 [西安]老一门(yyimen@foxmail.com) 提供的 565 格式说明。
  491. BMF.bfOffBits := BMF.bfOffBits + RGB565ExtDataLen;
  492. BMF.bfSize := BMF.bfSize + RGB565ExtDataLen;
  493. end;
  494. // FileSizeFix := 0;
  495. // if (BMF.bfSize mod 4) > 0 then
  496. // begin
  497. // FileSizeFix := 4 - BMF.bfSize mod 4;
  498. // end;
  499. // bufferSize := bufferSize + FileSizeFix;
  500. // BMF.bfSize := BMF.bfSize + FileSizeFix;
  501. // 保存bmp文件头
  502. AStream.WriteBuffer(BMF, Sizeof(BMF));
  503. // bmp信息头
  504. FillChar(BitmapInfo, Sizeof(BitmapInfo), 0);
  505. BitmapInfo.biSize := 40;
  506. // if (CurrBytesPerPixel = 2) then
  507. // begin
  508. // //AcdSee 不支持这种大小的 BitmapInfo
  509. // BitmapInfo.biSize := 40 + RGB565ExtDataLen;
  510. // end;
  511. BitmapInfo.biWidth := nBmpWidth;
  512. BitmapInfo.biHeight := nBmpHeight;
  513. BitmapInfo.biPlanes := 1;
  514. if CurrBytesPerPixel > 0 then
  515. begin
  516. BitmapInfo.biBitCount := CurrBytesPerPixel * 8;
  517. end
  518. else
  519. begin
  520. BitmapInfo.biBitCount := 1;
  521. end;
  522. BitmapInfo.biSizeImage := bufferSize;
  523. // if True then
  524. // begin
  525. // //96
  526. // BitmapInfo.biXPelsPerMeter := $0EC4;
  527. // BitmapInfo.biYPelsPerMeter := $0EC4;
  528. // end
  529. // else
  530. // begin
  531. // //72
  532. // BitmapInfo.biXPelsPerMeter := $0B12;
  533. // BitmapInfo.biYPelsPerMeter := $0B12;
  534. // end;
  535. BitmapInfo.biXPelsPerMeter := 0;
  536. BitmapInfo.biYPelsPerMeter := 0;
  537. if (CurrBytesPerPixel = 2) then
  538. begin
  539. //可以采用 RGB555 代替 RGB565
  540. BitmapInfo.biCompression := BI_BITFIELDS; //0是 555 3 是 565
  541. end;
  542. // 保存bmp信息头
  543. AStream.WriteBuffer(BitmapInfo, Sizeof(BitmapInfo));
  544. if (CurrBytesPerPixel = 2) then
  545. begin
  546. // 保存 565 RGB Mask
  547. A32BitData := RGB565_MASK_RED;
  548. AStream.WriteBuffer(A32BitData, Sizeof(A32BitData));
  549. A32BitData := RGB565_MASK_GREEN;
  550. AStream.WriteBuffer(A32BitData, Sizeof(A32BitData));
  551. A32BitData := RGB565_MASK_BLUE;
  552. AStream.WriteBuffer(A32BitData, Sizeof(A32BitData));
  553. if RGB565ExtDataLen >= 16 then
  554. begin
  555. A32BitData := 0;
  556. AStream.WriteBuffer(A32BitData, Sizeof(A32BitData));
  557. end;
  558. end;
  559. if (CurrBytesPerPixel = 0) or (CurrBytesPerPixel = 1) then
  560. begin
  561. //颜色表
  562. RGBQUAD.rgbBlue := 0;
  563. RGBQUAD.rgbGreen := 0;
  564. RGBQUAD.rgbRed := 0;
  565. RGBQUAD.rgbReserved := 0;
  566. if (CurrBytesPerPixel = 1) then
  567. begin
  568. for I := 0 to 255 do
  569. begin
  570. AStream.WriteBuffer(RGBQUAD, Sizeof(RGBQUAD));
  571. end;
  572. BitmapInfo.biClrUsed := $FF;
  573. end
  574. else
  575. begin
  576. AStream.WriteBuffer(RGBQUAD, Sizeof(RGBQUAD));
  577. RGBQUAD.rgbBlue := $FF;
  578. RGBQUAD.rgbGreen := $FF;
  579. RGBQUAD.rgbRed := $FF;
  580. RGBQUAD.rgbReserved := 0;
  581. AStream.WriteBuffer(RGBQUAD, Sizeof(RGBQUAD));
  582. BitmapInfo.biClrUsed := 2;
  583. end;
  584. end;
  585. // 像素扫描
  586. SetLength(bmpData, wWidth);
  587. {$IFDEF FMX}
  588. AlphaColorBuffer := GetMemory(nBmpWidth * SizeOf(TAlphaColor));
  589. try
  590. {$ENDIF}
  591. for nCol := nBmpHeight - 1 downto 0 do
  592. begin
  593. FillChar(bmpData[0], wWidth, 0);
  594. wByteIdex := 0;
  595. //0 是单色图
  596. if (CurrBytesPerPixel = 0) or (CurrBytesPerPixel = 1) then
  597. begin
  598. A8BitData := 0;
  599. ABitIndex := 0;
  600. {$IFDEF FMX}
  601. {$ELSE}
  602. Pixs := ScanLine[nCol];
  603. {$ENDIF}
  604. for wRow := 0 to nBmpWidth - 1 do
  605. begin
  606. {$IFDEF FMX}
  607. //X 是行坐标,Y 是 列坐标。
  608. clr := Data.GetPixel(wRow, nCol);
  609. {$ELSE}
  610. {$ENDIF}
  611. GrayeData := 0;
  612. {$IFDEF FMX}
  613. if MonochromeChangeType = TMonochromeChangeType.Average then
  614. begin
  615. GrayeData := TAlphaColorRec(clr).R + TAlphaColorRec(clr).G + TAlphaColorRec(clr).B;
  616. GrayeData := GrayeData div 3;
  617. end;
  618. if MonochromeChangeType = TMonochromeChangeType.Weighting then
  619. begin
  620. GrayeData := Round((TAlphaColorRec(clr).R * MonochromeChange_Weighting_Red +
  621. TAlphaColorRec(clr).G * MonochromeChange_Weighting_Green +
  622. TAlphaColorRec(clr).B * MonochromeChange_Weighting_Blue) / 3);
  623. end;
  624. if MonochromeChangeType = TMonochromeChangeType.Max then
  625. begin
  626. GrayeData := System.Math.Max(System.Math.Max(TAlphaColorRec(clr).R, TAlphaColorRec(clr).G),
  627. TAlphaColorRec(clr).B);
  628. end;
  629. {$ELSE}
  630. if MonochromeChangeType = TMonochromeChangeType.Average then
  631. begin
  632. GrayeData := Pixs[wRow].rgbtRed + Pixs[wRow].rgbtGreen + Pixs[wRow].rgbtBlue;
  633. GrayeData := GrayeData div 3;
  634. end;
  635. if MonochromeChangeType = TMonochromeChangeType.Weighting then
  636. begin
  637. GrayeData := Round((Pixs[wRow].rgbtRed * MonochromeChange_Weighting_Red +
  638. Pixs[wRow].rgbtGreen * MonochromeChange_Weighting_Green +
  639. Pixs[wRow].rgbtBlue * MonochromeChange_Weighting_Blue) / 3);
  640. end;
  641. if MonochromeChangeType = TMonochromeChangeType.Max then
  642. begin
  643. GrayeData := System.Math.Max(System.Math.Max(Pixs[wRow].rgbtRed, Pixs[wRow].rgbtGreen),
  644. Pixs[wRow].rgbtBlue);
  645. end;
  646. {$ENDIF}
  647. if GrayeData > MonochromeChange_Threshold then
  648. begin
  649. A8BitData := A8BitData or ($80 shr ABitIndex);
  650. end;
  651. inc(ABitIndex);
  652. if ABitIndex > 7 then
  653. begin
  654. ABitIndex := 0;
  655. if (CurrBytesPerPixel = 0) then
  656. begin
  657. bmpData[wByteIdex] := A8BitData;
  658. A8BitData := 0;
  659. inc(wByteIdex);
  660. end;
  661. end;
  662. end;
  663. if (CurrBytesPerPixel = 0) then
  664. begin
  665. if ABitIndex > 0 then
  666. begin
  667. bmpData[wByteIdex] := A8BitData;
  668. A8BitData := 0;
  669. end;
  670. end;
  671. end
  672. else
  673. begin
  674. {$IFDEF FMX}
  675. // for wRow := 0 to nBmpWidth - 1 do
  676. // begin
  677. // //X 是行坐标,Y 是 列坐标。
  678. // clr := Data.GetPixel(wRow, nCol);
  679. // case CurrBytesPerPixel of
  680. // 1:
  681. // begin
  682. // //不支持。
  683. // end;
  684. // 2:
  685. // begin
  686. // A16BitData := rgb_24_2_565(TAlphaColorRec(clr).R, TAlphaColorRec(clr).G, TAlphaColorRec(clr).B);
  687. // bmpData[wByteIdex + 0] := WordRec(A16BitData).Lo;
  688. // bmpData[wByteIdex + 1] := WordRec(A16BitData).Hi;
  689. // end;
  690. // 3,4:
  691. // begin
  692. // bmpData[wByteIdex + 0] := TAlphaColorRec(clr).B;
  693. // bmpData[wByteIdex + 1] := TAlphaColorRec(clr).G;
  694. // bmpData[wByteIdex + 2] := TAlphaColorRec(clr).R;
  695. // end;
  696. // end;
  697. // if CurrBytesPerPixel = 4 then
  698. // begin
  699. // bmpData[wByteIdex + 3] := TAlphaColorRec(clr).A;
  700. // end;
  701. // Inc(wByteIdex, CurrBytesPerPixel);
  702. // end;
  703. case CurrBytesPerPixel of
  704. 1:
  705. begin
  706. //不支持。
  707. end;
  708. 2:
  709. begin
  710. ScanlineToAlphaColor(Data.GetScanline(nCol), AlphaColorBuffer, nBmpWidth, Data.PixelFormat);
  711. AlphaColorToScanline(AlphaColorBuffer, Addr(bmpData[0]), nBmpWidth, TPixelFormat.BGR_565);
  712. end;
  713. 3:
  714. begin
  715. ScanlineToAlphaColor(Data.GetScanline(nCol), AlphaColorBuffer, nBmpWidth, Data.PixelFormat);
  716. AlphaColorToScanline(AlphaColorBuffer, Addr(bmpData[0]), nBmpWidth, TPixelFormat.BGR);
  717. end;
  718. 4:
  719. begin
  720. if Data.PixelFormat = TPixelFormat.BGRA then
  721. begin
  722. Move(PByte(Data.GetScanline(nCol))[0], bmpData[0], Data.BytesPerPixel * nBmpWidth);
  723. end
  724. else
  725. begin
  726. ScanlineToAlphaColor(Data.GetScanline(nCol), AlphaColorBuffer, nBmpWidth, Data.PixelFormat);
  727. AlphaColorToScanline(AlphaColorBuffer, Addr(bmpData[0]), nBmpWidth, TPixelFormat.BGRA);
  728. end;
  729. end;
  730. end;
  731. {$ELSE}
  732. Pixs := ScanLine[nCol];
  733. for wRow := 0 to nBmpWidth - 1 do
  734. begin
  735. case CurrBytesPerPixel of
  736. 1:
  737. begin
  738. //不支持。
  739. end;
  740. 2:
  741. begin
  742. A16BitData := rgb_24_2_565(Pixs[wRow].rgbtRed, Pixs[wRow].rgbtGreen, Pixs[wRow].rgbtBlue);
  743. bmpData[wByteIdex + 0] := WordRec(A16BitData).Lo;
  744. bmpData[wByteIdex + 1] := WordRec(A16BitData).Hi;
  745. end;
  746. 3,4:
  747. begin
  748. bmpData[wByteIdex + 0] := Pixs[wRow].rgbtBlue;
  749. bmpData[wByteIdex + 1] := Pixs[wRow].rgbtGreen;
  750. bmpData[wByteIdex + 2] := Pixs[wRow].rgbtRed;
  751. end;
  752. end;
  753. if CurrBytesPerPixel = 4 then
  754. begin
  755. bmpData[wByteIdex + 3] := $FF;
  756. end;
  757. Inc(wByteIdex, CurrBytesPerPixel);
  758. end;
  759. {$ENDIF}
  760. end;
  761. AStream.WriteBuffer(bmpData, wWidth);
  762. end;
  763. {$IFDEF FMX}
  764. finally
  765. FreeMemory(AlphaColorBuffer);
  766. end;
  767. {$ENDIF}
  768. // A8BitData := 0;
  769. // for I := 0 to FileSizeFix - 1 do
  770. // begin
  771. // AStream.WriteBuffer(A8BitData, 1);
  772. // end;
  773. Result := True;
  774. finally
  775. {$IFDEF FMX}
  776. Unmap(Data);
  777. {$ELSE}
  778. {$ENDIF}
  779. end;
  780. end;
  781. procedure TKngStrBitmapHelper.SaveAsBMPToStreamDef(Stream: TStream);
  782. begin
  783. if not SaveAsBMPToStream(Stream) then
  784. begin
  785. {$IFDEF FMX}
  786. raise EBitmapSavingFailed.Create(SBitmapSavingFailed);
  787. {$ELSE}
  788. raise EInvalidGraphicOperation.Create(SBitmapSavingFailed);
  789. {$ENDIF}
  790. end;
  791. end;
  792. {$IFDEF FMX}
  793. procedure TKngStrBitmapHelper.SyncAssign(Source: TPersistent);
  794. begin
  795. TThread.Synchronize(nil,
  796. procedure
  797. begin
  798. Assign(Source);
  799. end)
  800. end;
  801. procedure TKngStrBitmapHelper.SyncLoadFromFile(const AFileName: string);
  802. var
  803. Surf: TBitmapSurface;
  804. begin
  805. Surf := TBitmapSurface.Create;
  806. try
  807. if TBitmapCodecManager.LoadFromFile(AFileName, Surf, CanvasClass.GetAttribute(TCanvasAttribute.MaxBitmapSize)) then
  808. TThread.Synchronize(nil,
  809. procedure
  810. begin
  811. Assign(Surf);
  812. end)
  813. else
  814. raise EBitmapLoadingFailed.CreateFMT(SBitmapLoadingFailedNamed, [AFileName]);
  815. finally
  816. Surf.Free;
  817. end;
  818. end;
  819. procedure TKngStrBitmapHelper.SyncLoadFromStream(Stream: TStream);
  820. var
  821. S: TStream;
  822. Surf: TBitmapSurface;
  823. begin
  824. if Stream.Position > 0 then
  825. begin
  826. // need to create temp stream
  827. S := TMemoryStream.Create;
  828. try
  829. S.CopyFrom(Stream, Stream.Size - Stream.Position);
  830. S.Position := 0;
  831. Surf := TBitmapSurface.Create;
  832. try
  833. if TBitmapCodecManager.LoadFromStream(S, Surf, CanvasClass.GetAttribute(TCanvasAttribute.MaxBitmapSize)) then
  834. TThread.Synchronize(nil,
  835. procedure
  836. begin
  837. Assign(Surf);
  838. end)
  839. else
  840. raise EBitmapLoadingFailed.Create(SBitmapLoadingFailed);
  841. finally
  842. Surf.Free;
  843. end;
  844. finally
  845. S.Free;
  846. end;
  847. end
  848. else
  849. if Stream.Size = 0 then
  850. Clear(0)
  851. else begin
  852. Surf := TBitmapSurface.Create;
  853. try
  854. if TBitmapCodecManager.LoadFromStream(Stream, Surf, CanvasClass.GetAttribute(TCanvasAttribute.MaxBitmapSize)) then
  855. TThread.Synchronize(nil,
  856. procedure
  857. begin
  858. Assign(Surf);
  859. end)
  860. else
  861. raise EBitmapLoadingFailed.Create(SBitmapLoadingFailed);
  862. finally
  863. Surf.Free;
  864. end;
  865. end;
  866. end;
  867. procedure TKngStrBitmapHelper.SyncLoadThumbnailFromFile(const AFileName: string; const AFitWidth, AFitHeight: Single;
  868. const UseEmbedded: Boolean = True);
  869. var
  870. Surf: TBitmapSurface;
  871. begin
  872. Surf := TBitmapSurface.Create;
  873. try
  874. if TBitmapCodecManager.LoadThumbnailFromFile(AFileName, AFitWidth, AFitHeight, UseEmbedded, Surf) then
  875. TThread.Synchronize(nil,
  876. procedure
  877. begin
  878. Assign(Surf);
  879. end)
  880. else
  881. raise EThumbnailLoadingFailed.CreateFMT(SThumbnailLoadingFailedNamed, [AFileName]);
  882. finally
  883. Surf.Free;
  884. end;
  885. end;
  886. function TKngStrBitmapHelper.SyncLoadThumbnailFromStream(const AStream: TStream;
  887. const ASrc, ADest: TRectF; const UseEmbedded: Boolean): Boolean;
  888. var
  889. S: TStream;
  890. Surf: TBitmapSurface;
  891. begin
  892. if AStream.Position > 0 then
  893. begin
  894. // need to create temp stream
  895. S := TMemoryStream.Create;
  896. try
  897. S.CopyFrom(AStream, AStream.Size - AStream.Position);
  898. S.Position := 0;
  899. Surf := TBitmapSurface.Create;
  900. try
  901. if TBitmapCodecManager.LoadThumbnailFromStream(S, ASrc, ADest, UseEmbedded, Surf) then
  902. TThread.Synchronize(nil,
  903. procedure
  904. begin
  905. Assign(Surf);
  906. end)
  907. else
  908. raise EBitmapLoadingFailed.Create(SThumbnailLoadingFailed);
  909. finally
  910. Surf.Free;
  911. end;
  912. finally
  913. S.Free;
  914. end;
  915. end
  916. else
  917. if AStream.Size = 0 then
  918. Clear(0)
  919. else begin
  920. Surf := TBitmapSurface.Create;
  921. try
  922. if TBitmapCodecManager.LoadThumbnailFromStream(AStream, ASrc, ADest, UseEmbedded, Surf) then
  923. TThread.Synchronize(nil,
  924. procedure
  925. begin
  926. Assign(Surf);
  927. end)
  928. else
  929. raise EBitmapLoadingFailed.Create(SThumbnailLoadingFailed);
  930. finally
  931. Surf.Free;
  932. end;
  933. end;
  934. end;
  935. procedure TKngStrBitmapHelper.SyncLoadThumbnailFromStream(const Stream: TStream;
  936. const AFitWidth, AFitHeight: Single; const UseEmbedded: Boolean; const AutoCut: Boolean);
  937. var
  938. S: TStream;
  939. Surf: TBitmapSurface;
  940. begin
  941. if Stream.Position > 0 then
  942. begin
  943. // need to create temp stream
  944. S := TMemoryStream.Create;
  945. try
  946. S.CopyFrom(Stream, Stream.Size - Stream.Position);
  947. S.Position := 0;
  948. Surf := TBitmapSurface.Create;
  949. try
  950. if TBitmapCodecManager.LoadThumbnailFromStream(S, AFitWidth, AFitHeight, UseEmbedded, AutoCut, Surf) then
  951. TThread.Synchronize(nil,
  952. procedure
  953. begin
  954. Assign(Surf);
  955. end)
  956. else
  957. raise EBitmapLoadingFailed.Create(SThumbnailLoadingFailed);
  958. finally
  959. Surf.Free;
  960. end;
  961. finally
  962. S.Free;
  963. end;
  964. end
  965. else
  966. if Stream.Size = 0 then
  967. Clear(0)
  968. else begin
  969. Surf := TBitmapSurface.Create;
  970. try
  971. if TBitmapCodecManager.LoadThumbnailFromStream(Stream, AFitWidth, AFitHeight, UseEmbedded, AutoCut, Surf) then
  972. TThread.Synchronize(nil,
  973. procedure
  974. begin
  975. Assign(Surf);
  976. end)
  977. else
  978. raise EBitmapLoadingFailed.Create(SThumbnailLoadingFailed);
  979. finally
  980. Surf.Free;
  981. end;
  982. end;
  983. end;
  984. { TKngStrBitmapCodecManager }
  985. class function TKngStrBitmapCodecManager.GetImageSize(const AStream: TStream): TPointF;
  986. var
  987. CodecClass: TCustomBitmapCodecClass;
  988. DataType: String;
  989. begin
  990. DataType := TImageTypeChecker.GetType(AStream);
  991. CodecClass := GuessCodecClass(DataType, TBitmapCodecDescriptorField.Extension);
  992. if CodecClass <> nil then
  993. {$IFDEF ANDROID}
  994. Result := TBitmapCodecAndroid(CodecClass).GetImageSize(AStream)
  995. {$ELSE}
  996. Result := TBitmapCodecWIC(CodecClass).GetImageSize(AStream)
  997. {$ENDIF}
  998. else
  999. Result := TPointF.Zero;
  1000. end;
  1001. class function TKngStrBitmapCodecManager.GetImageSize(const AFileName: string): TPointF;
  1002. begin
  1003. Result := inherited GetImageSize(AFileName);
  1004. end;
  1005. class function TKngStrBitmapCodecManager.GuessCodecClass(const Name: string;
  1006. const Field: TBitmapCodecDescriptorField): TCustomBitmapCodecClass;
  1007. type
  1008. TPrivateMethodType = function (const Name: string; const Field: TBitmapCodecDescriptorField):
  1009. TCustomBitmapCodecClass of object;
  1010. var
  1011. AMethod: TMethod;
  1012. AInvoke: TPrivateMethodType absolute AMethod;
  1013. begin
  1014. AMethod.Code := @TBitmapCodecManager.GuessCodecClass;
  1015. AMethod.Data := Self;
  1016. Result := AInvoke(Name, Field);
  1017. end;
  1018. class function TKngStrBitmapCodecManager.LoadFromStream(const AStream: TStream;
  1019. const Bitmap: TBitmapSurface; const MaxSizeLimit: Cardinal): Boolean;
  1020. var
  1021. CodecClass: TCustomBitmapCodecClass;
  1022. Codec: TCustomBitmapCodec;
  1023. DataType: String;
  1024. begin
  1025. Result := False;
  1026. DataType := TImageTypeChecker.GetType(AStream);
  1027. CodecClass := GuessCodecClass(DataType, TBitmapCodecDescriptorField.Extension);
  1028. if CodecClass <> nil then
  1029. begin
  1030. Codec := CodecClass.Create;
  1031. try
  1032. {$IFDEF ANDROID}
  1033. Result := TBitmapCodecAndroid(Codec).LoadFromStream(AStream, Bitmap, MaxSizeLimit);
  1034. {$ELSE}
  1035. Result := TBitmapCodecWIC(Codec).LoadFromStream(AStream, Bitmap, MaxSizeLimit);
  1036. {$ENDIF}
  1037. finally
  1038. Codec.Free;
  1039. end;
  1040. end
  1041. end;
  1042. class function TKngStrBitmapCodecManager.LoadThumbnailFromStream(
  1043. const AStream: TStream; const ASrc, ADest: TRectF; const UseEmbedded: Boolean;
  1044. const Bitmap: TBitmapSurface): Boolean;
  1045. var
  1046. CodecClass: TCustomBitmapCodecClass;
  1047. Codec: TCustomBitmapCodec;
  1048. DataType: String;
  1049. begin
  1050. Result := False;
  1051. DataType := TImageTypeChecker.GetType(AStream);
  1052. CodecClass := GuessCodecClass(DataType, TBitmapCodecDescriptorField.Extension);
  1053. if CodecClass <> nil then
  1054. begin
  1055. Codec := CodecClass.Create;
  1056. try
  1057. {$IFDEF ANDROID}
  1058. Result := TBitmapCodecAndroid(Codec).LoadThumbnailFromStream(AStream, ASrc, ADest, UseEmbedded, Bitmap);
  1059. {$ELSE}
  1060. Result := TBitmapCodecWIC(Codec).LoadThumbnailFromStream(AStream, ASrc, ADest, UseEmbedded, Bitmap);
  1061. {$ENDIF}
  1062. finally
  1063. Codec.Free;
  1064. end;
  1065. end
  1066. end;
  1067. class function TKngStrBitmapCodecManager.LoadThumbnailFromStream(
  1068. const AStream: TStream; const AFitWidth, AFitHeight: Single;
  1069. const UseEmbedded: Boolean; const AutoCut: Boolean;
  1070. const Bitmap: TBitmapSurface): Boolean;
  1071. var
  1072. CodecClass: TCustomBitmapCodecClass;
  1073. Codec: TCustomBitmapCodec;
  1074. DataType: String;
  1075. begin
  1076. Result := False;
  1077. DataType := TImageTypeChecker.GetType(AStream);
  1078. CodecClass := GuessCodecClass(DataType, TBitmapCodecDescriptorField.Extension);
  1079. if CodecClass <> nil then
  1080. begin
  1081. Codec := CodecClass.Create;
  1082. try
  1083. {$IFDEF ANDROID}
  1084. Result := TBitmapCodecAndroid(Codec).LoadThumbnailFromStream(AStream, AFitWidth, AFitHeight, UseEmbedded, AutoCut, Bitmap);
  1085. {$ELSE}
  1086. Result := TBitmapCodecWIC(Codec).LoadThumbnailFromStream(AStream, AFitWidth, AFitHeight, UseEmbedded, AutoCut, Bitmap);
  1087. {$ENDIF}
  1088. finally
  1089. Codec.Free;
  1090. end;
  1091. end
  1092. end;
  1093. {$IFDEF ANDROID}
  1094. { TBitmapCodecAndroid }
  1095. class function TBitmapCodecAndroid.GetMovieSize(const Stream: TStream): TPoint;
  1096. type
  1097. TPrivateMethodType = function (const Stream: TStream): TPoint of object;
  1098. var
  1099. AMethod: TMethod;
  1100. AInvoke: TPrivateMethodType absolute AMethod;
  1101. begin
  1102. AMethod.Code := @TBitmapCodecAndroid.GetMovieSize;
  1103. AMethod.Data := Self;
  1104. Result := AInvoke(Stream);
  1105. end;
  1106. class function TBitmapCodecAndroid.GetImageSize(const AStream: TStream): TPointF;
  1107. var
  1108. TempStream: TMemoryStream;
  1109. TempArray: TJavaArray<Byte>;
  1110. NativeBitmap: JBitmap;
  1111. LoadOptions: JBitmapFactory_Options;
  1112. SavePosition: Int64;
  1113. begin
  1114. if IsGIFStream(AStream) then
  1115. Result := GetMovieSize(AStream)
  1116. else begin
  1117. SavePosition := AStream.Position;
  1118. try
  1119. TempStream := TMemoryStream.Create;
  1120. try
  1121. TempStream.CopyFrom(AStream, AStream.Size);
  1122. TempArray := TJavaArray<Byte>.Create(TempStream.Size);
  1123. Move(TempStream.Memory^, TempArray.Data^, TempStream.Size);
  1124. finally
  1125. TempStream.Free;
  1126. end;
  1127. LoadOptions := TJBitmapFactory_Options.JavaClass.init;
  1128. LoadOptions.inJustDecodeBounds := True;
  1129. TJBitmapFactory.JavaClass.decodeByteArray(TempArray, 0, TempArray.Length, LoadOptions);
  1130. TempArray := nil;
  1131. Result := TPointF.Create(LoadOptions.outWidth, LoadOptions.outHeight);
  1132. finally
  1133. AStream.Position := SavePosition;
  1134. end;
  1135. end;
  1136. end;
  1137. class function TBitmapCodecAndroid.GetImageSize(const AFileName: string): TPointF;
  1138. begin
  1139. Result := inherited GetImageSize(AFileName);
  1140. end;
  1141. class function TBitmapCodecAndroid.IsGIFStream(const Stream: TStream): Boolean;
  1142. begin
  1143. Result := TImageTypeChecker.GetType(Stream) = SGIFImageExtension;
  1144. end;
  1145. function TBitmapCodecAndroid.LoadMovieFromStream(const Stream: TStream; const Surface: TBitmapSurface): Boolean;
  1146. var
  1147. PrevPosition: Int64;
  1148. TempArray: TJavaArray<Byte>;
  1149. Movie: JMovie;
  1150. Bitmap: JBitmap;
  1151. Canvas: JCanvas;
  1152. begin
  1153. PrevPosition := Stream.Position;
  1154. try
  1155. TempArray := TJavaArray<Byte>.Create(Stream.Size - Stream.Position);
  1156. Stream.ReadBuffer(TempArray.Data^, TempArray.Length);
  1157. finally
  1158. Stream.Position := PrevPosition;
  1159. end;
  1160. Movie := TJMovie.JavaClass.decodeByteArray(TempArray, 0, TempArray.Length);
  1161. TempArray := nil;
  1162. Bitmap := TJBitmap.JavaClass.createBitmap(Movie.width, Movie.height, TJBitmap_Config.JavaClass.ARGB_8888);
  1163. //kngstr
  1164. if Bitmap = nil then
  1165. Exit(False);
  1166. try
  1167. Canvas := TJCanvas.JavaClass.init(Bitmap);
  1168. try
  1169. Movie.setTime(0);
  1170. Movie.draw(Canvas, 0, 0);
  1171. finally
  1172. Canvas := nil;
  1173. end;
  1174. Result := JBitmapToSurface(Bitmap, Surface);
  1175. finally
  1176. Bitmap.recycle;
  1177. end;
  1178. end;
  1179. function TBitmapCodecAndroid.StretchIfNeed(const SrcBitmap: JBitmap; const Bitmap: TBitmapSurface;
  1180. const LoadOptions: JBitmapFactory_Options; const MaxSizeLimit: Cardinal): Boolean;
  1181. var
  1182. R: TRectF;
  1183. ScaledBitmap: JBitmap;
  1184. begin
  1185. if (MaxSizeLimit > 0) and ((LoadOptions.outWidth > Integer(MaxSizeLimit)) or
  1186. (LoadOptions.outHeight > Integer(MaxSizeLimit))) then
  1187. begin
  1188. R := TRectF.Create(0, 0, LoadOptions.outWidth, LoadOptions.outHeight);
  1189. R.Fit(TRectF.Create(0, 0, MaxSizeLimit, MaxSizeLimit));
  1190. ScaledBitmap := TJBitmap.JavaClass.createScaledBitmap(SrcBitmap, R.Truncate.Width, R.Truncate.Height, True);
  1191. //kngstr
  1192. if ScaledBitmap = nil then
  1193. Exit(False);
  1194. try
  1195. Result := JBitmapToSurface(ScaledBitmap, Bitmap);
  1196. finally
  1197. ScaledBitmap.recycle;
  1198. end;
  1199. end
  1200. else
  1201. Result := JBitmapToSurface(SrcBitmap, Bitmap);
  1202. end;
  1203. function TBitmapCodecAndroid.LoadFromStream(const AStream: TStream;
  1204. const Bitmap: TBitmapSurface; const MaxSizeLimit: Cardinal): Boolean;
  1205. var
  1206. TempStream: TMemoryStream;
  1207. TempArray: TJavaArray<Byte>;
  1208. NativeBitmap: JBitmap;
  1209. LoadOptions: JBitmapFactory_Options;
  1210. SavePosition: Int64;
  1211. begin
  1212. if IsGIFStream(AStream) then
  1213. Result := LoadMovieFromStream(AStream, Bitmap)
  1214. else
  1215. begin
  1216. SavePosition := AStream.Position;
  1217. try
  1218. TempStream := TMemoryStream.Create;
  1219. try
  1220. TempStream.CopyFrom(AStream, AStream.Size);
  1221. TempArray := TJavaArray<Byte>.Create(TempStream.Size);
  1222. Move(TempStream.Memory^, TempArray.Data^, TempStream.Size);
  1223. finally
  1224. TempStream.Free;
  1225. end;
  1226. LoadOptions := TJBitmapFactory_Options.JavaClass.init;
  1227. NativeBitmap := TJBitmapFactory.JavaClass.decodeByteArray(TempArray, 0, TempArray.Length, LoadOptions);
  1228. TempArray := nil;
  1229. //kngstr
  1230. if NativeBitmap = nil then
  1231. Exit(False);
  1232. try
  1233. if (LoadOptions.outWidth < 1) or (LoadOptions.outHeight < 1) then
  1234. Exit(False);
  1235. Result := StretchIfNeed(NativeBitmap, Bitmap, LoadOptions, MaxSizeLimit);
  1236. finally
  1237. NativeBitmap.recycle;
  1238. end;
  1239. finally
  1240. AStream.Position := SavePosition;
  1241. end;
  1242. end;
  1243. end;
  1244. function TBitmapCodecAndroid.LoadMovieFromStreamScaled(const AStream: TStream; const Surface: TBitmapSurface;
  1245. const FitSize: TPoint): Boolean;
  1246. var
  1247. TempStream: TMemoryStream;
  1248. TempArray: TJavaArray<Byte>;
  1249. Movie: JMovie;
  1250. OrigBitmap, Bitmap: JBitmap;
  1251. Canvas: JCanvas;
  1252. OrigSize: TPoint;
  1253. LoadOptions: JBitmapFactory_Options;
  1254. SavePosition: Int64;
  1255. begin
  1256. SavePosition := AStream.Position;
  1257. try
  1258. TempStream := TMemoryStream.Create;
  1259. try
  1260. TempStream.CopyFrom(AStream, AStream.Size);
  1261. TempArray := TJavaArray<Byte>.Create(TempStream.Size);
  1262. Move(TempStream.Memory^, TempArray.Data^, TempStream.Size);
  1263. finally
  1264. TempStream.Free;
  1265. end;
  1266. Movie := TJMovie.JavaClass.decodeByteArray(TempArray, 0, TempArray.Length);
  1267. TempArray := nil;
  1268. OrigSize := TPoint.Create(Movie.width, Movie.height);
  1269. OrigBitmap := TJBitmap.JavaClass.createBitmap(OrigSize.X, OrigSize.Y, TJBitmap_Config.JavaClass.ARGB_8888);
  1270. if OrigBitmap = nil then //kngstr fixed
  1271. Exit(False);
  1272. try
  1273. Canvas := TJCanvas.JavaClass.init(OrigBitmap);
  1274. try
  1275. Movie.setTime(0);
  1276. Movie.draw(Canvas, 0, 0);
  1277. finally
  1278. Canvas := nil;
  1279. end;
  1280. Movie := nil;
  1281. Bitmap := TJBitmap.JavaClass.createBitmap(FitSize.X, FitSize.Y, TJBitmap_Config.JavaClass.ARGB_8888);
  1282. if Bitmap = nil then //kngstr fixed
  1283. Exit(False);
  1284. try
  1285. Canvas := TJCanvas.JavaClass.init(Bitmap);
  1286. try
  1287. Canvas.drawBitmap(OrigBitmap, TJRect.JavaClass.init(0, 0, OrigSize.X, OrigSize.Y), TJRect.JavaClass.init(0, 0,
  1288. FitSize.X, FitSize.y), nil);
  1289. finally
  1290. Canvas := nil;
  1291. end;
  1292. Result := JBitmapToSurface(Bitmap, Surface);
  1293. finally
  1294. Bitmap.recycle; //kngstr fixed
  1295. end;
  1296. finally
  1297. OrigBitmap.recycle;
  1298. end;
  1299. finally
  1300. AStream.Position := SavePosition;
  1301. end;
  1302. end;
  1303. //连续decode需要reset
  1304. //https://blog.csdn.net/boystray/article/details/77725648
  1305. //多图加载的优化
  1306. //https://blog.csdn.net/Android_app/article/details/45815093
  1307. //inSampleSize优化
  1308. //https://www.jianshu.com/p/f15cd2ed6ec0
  1309. procedure calculateInSampleSize(options: JBitmapFactory_Options; reqWidth, reqHeight: Integer);
  1310. var
  1311. width, height, suitedValue: Integer;
  1312. widthRatio, heightRatio: Integer;
  1313. begin
  1314. options.inSampleSize := 1;
  1315. width := options.outWidth;
  1316. height := options.outHeight;
  1317. if (height > reqHeight) or (width > reqWidth) then begin
  1318. //使用需要的宽高的最大值来计算比率
  1319. if reqHeight > reqWidth then
  1320. suitedValue := reqHeight
  1321. else
  1322. suitedValue := reqWidth;
  1323. heightRatio := height div suitedValue;
  1324. widthRatio := width div suitedValue;
  1325. if heightRatio > widthRatio then //用最大
  1326. options.inSampleSize := heightRatio
  1327. else
  1328. options.inSampleSize := widthRatio;
  1329. end;
  1330. end;
  1331. function TBitmapCodecAndroid.LoadThumbnailFromStream(const AStream: TStream;
  1332. const ASrc, ADest: TRectF; const UseEmbedded: Boolean;
  1333. const Bitmap: TBitmapSurface): Boolean;
  1334. var
  1335. TempStream: TMemoryStream;
  1336. TempArray: TJavaArray<Byte>;
  1337. NativeBitmap1, NativeBitmap2: JBitmap;
  1338. LoadOptions: JBitmapFactory_Options;
  1339. SavePosition: Int64;
  1340. begin
  1341. if IsGIFStream(AStream) then
  1342. Result := LoadMovieFromStreamScaled(AStream, Bitmap, TPoint.Create(Round(ADest.Width), Round(ADest.Height)))
  1343. else
  1344. begin
  1345. SavePosition := AStream.Position;
  1346. try
  1347. TempStream := TMemoryStream.Create;
  1348. try
  1349. TempStream.CopyFrom(AStream, AStream.Size);
  1350. TempArray := TJavaArray<Byte>.Create(TempStream.Size);
  1351. Move(TempStream.Memory^, TempArray.Data^, TempStream.Size);
  1352. finally
  1353. TempStream.Free;
  1354. end;
  1355. LoadOptions := TJBitmapFactory_Options.JavaClass.init;
  1356. LoadOptions.inJustDecodeBounds := False;
  1357. NativeBitmap1 := TJBitmapFactory.JavaClass.decodeByteArray(TempArray, 0, TempArray.Length, LoadOptions);
  1358. TempArray := nil;
  1359. //kngstr
  1360. if NativeBitmap1 = nil then
  1361. Exit(False);
  1362. try
  1363. if (LoadOptions.outWidth < 1) or (LoadOptions.outHeight < 1) then
  1364. Exit(False);
  1365. // 剪裁
  1366. if (not ASrc.IsEmpty) and (ASrc.Width < LoadOptions.outWidth) and (ASrc.Height < LoadOptions.outHeight) then begin
  1367. NativeBitmap2 := TJBitmap.JavaClass.createBitmap(NativeBitmap1, Round(ASrc.Left), Round(ASrc.Top), Round(ASrc.Width), Round(ASrc.Height));
  1368. //kngstr
  1369. if NativeBitmap2 = nil then
  1370. Exit(False);
  1371. NativeBitmap1.recycle;
  1372. NativeBitmap1 := nil;
  1373. NativeBitmap1 := NativeBitmap2;
  1374. end;
  1375. //缩放
  1376. NativeBitmap2 := TJBitmap.JavaClass.createScaledBitmap(NativeBitmap1, Round(ADest.Width), Round(ADest.Height), True);
  1377. //kngstr
  1378. if NativeBitmap2 = nil then
  1379. Exit(False);
  1380. try
  1381. Result := JBitmapToSurface(NativeBitmap2, Bitmap)
  1382. finally
  1383. NativeBitmap2.recycle;
  1384. end;
  1385. finally
  1386. NativeBitmap1.recycle;
  1387. end;
  1388. finally
  1389. AStream.Position := SavePosition;
  1390. end;
  1391. end;
  1392. end;
  1393. function TBitmapCodecAndroid.LoadThumbnailFromStream(const AStream: TStream;
  1394. const AFitWidth, AFitHeight: Single; const UseEmbedded: Boolean;
  1395. const AutoCut: Boolean; const Bitmap: TBitmapSurface): Boolean;
  1396. var
  1397. TempStream: TMemoryStream;
  1398. TempArray: TJavaArray<Byte>;
  1399. NativeBitmap1, NativeBitmap2, NativeBitmap3: JBitmap;
  1400. LoadOptions: JBitmapFactory_Options;
  1401. SavePosition: Int64;
  1402. X, Y, W, H: Integer;
  1403. begin
  1404. if IsGIFStream(AStream) then
  1405. Result := LoadMovieFromStreamScaled(AStream, Bitmap, TPoint.Create(Round(AFitWidth), Round(AFitHeight)))
  1406. else
  1407. begin
  1408. SavePosition := AStream.Position;
  1409. try
  1410. TempStream := TMemoryStream.Create;
  1411. try
  1412. TempStream.CopyFrom(AStream, AStream.Size);
  1413. TempArray := TJavaArray<Byte>.Create(TempStream.Size);
  1414. Move(TempStream.Memory^, TempArray.Data^, TempStream.Size);
  1415. finally
  1416. TempStream.Free;
  1417. end;
  1418. LoadOptions := TJBitmapFactory_Options.JavaClass.init;
  1419. //读取文件大小
  1420. LoadOptions.inJustDecodeBounds := True;
  1421. TJBitmapFactory.JavaClass.decodeByteArray(TempArray, 0, TempArray.Length, LoadOptions);
  1422. //计算缩略尺寸
  1423. calculateInSampleSize(LoadOptions, Round(AFitWidth), Round(AFitHeight));
  1424. LoadOptions.inJustDecodeBounds := False;
  1425. NativeBitmap1 := TJBitmapFactory.JavaClass.decodeByteArray(TempArray, 0, TempArray.Length, LoadOptions);
  1426. TempArray := nil;
  1427. //kngstr
  1428. if NativeBitmap1 = nil then
  1429. Exit(False);
  1430. try
  1431. if (LoadOptions.outWidth < 1) or (LoadOptions.outHeight < 1) then
  1432. Exit(False);
  1433. NativeBitmap2 := TJBitmap.JavaClass.createScaledBitmap(NativeBitmap1, Round(AFitWidth), Round(AFitHeight), True);
  1434. //kngstr
  1435. if NativeBitmap2 = nil then
  1436. Exit(False);
  1437. try
  1438. if not AutoCut then
  1439. Result := JBitmapToSurface(NativeBitmap2, Bitmap)
  1440. else begin //临时处理下,截取大图的中间部分,尤其是分辨率特别大的
  1441. X := 0;
  1442. Y := 0;
  1443. W := Round(AFitWidth);
  1444. H := Round(AFitHeight);
  1445. if W > H then begin
  1446. X := (W - H) div 2;
  1447. W := H;
  1448. end
  1449. else if W < H then begin
  1450. Y := (H - W) div 2;
  1451. H := W;
  1452. end;
  1453. NativeBitmap3 := TJBitmap.JavaClass.createBitmap(NativeBitmap2, X, Y, W, H);
  1454. //kngstr
  1455. if NativeBitmap3 = nil then
  1456. Exit(False);
  1457. try
  1458. Result := JBitmapToSurface(NativeBitmap3, Bitmap);
  1459. finally
  1460. NativeBitmap3.recycle;
  1461. end;
  1462. end;
  1463. finally
  1464. NativeBitmap2.recycle;
  1465. end;
  1466. finally
  1467. NativeBitmap1.recycle;
  1468. end;
  1469. finally
  1470. AStream.Position := SavePosition;
  1471. end;
  1472. end;
  1473. end;
  1474. {$ENDIF}
  1475. {$ENDIF}
  1476. {$IFDEF FMX}
  1477. { TBitmap16bitFiler }
  1478. class constructor TBitmap16bitFiler.Create;
  1479. var
  1480. i: integer;
  1481. begin
  1482. i := 0;
  1483. while i < $10000 do
  1484. begin
  1485. // 不用for因为优化会将循环变量的值保存在寄存器不更新到内存
  1486. Color[i] := PixelToAlphaColor(@i, TPixelFormat.BGR_565);
  1487. inc(i);
  1488. end;
  1489. end;
  1490. class procedure TBitmap16bitFiler.FillScanLine(D: TBitmapData;
  1491. ScanLine, Width: integer; data: Pointer);
  1492. var
  1493. SC: PAlphaColorArray;
  1494. DA: PWordArray;
  1495. I: Integer;
  1496. MinWidth: Integer;
  1497. begin
  1498. SC := D.GetScanline(ScanLine);
  1499. DA := data;
  1500. MinWidth := D.Width;
  1501. if (Width > 0) and (Width < MinWidth) then
  1502. MinWidth := Width;
  1503. for I := 0 to MinWidth - 1 do
  1504. begin
  1505. if D.PixelFormat = TPixelFormat.BGRA then
  1506. begin
  1507. SC[I] := Color[DA[I]];
  1508. end
  1509. else
  1510. begin
  1511. AlphaColorToPixel(Color[DA[I]], Addr(SC[I]), D.PixelFormat);
  1512. end;
  1513. end;
  1514. end;
  1515. function FillScanLineFormMemory(BitmapData: TBitmapData; ScanLineIndex, Width: integer;
  1516. InputData: Pointer; InputFormat: TPixelFormat): Boolean;
  1517. var
  1518. SC: PAlphaColorArray;
  1519. Buffer: PAlphaColor;
  1520. MinWidth: Integer;
  1521. begin
  1522. Result := False;
  1523. if ScanLineIndex < 0 then exit;
  1524. if ScanLineIndex >= BitmapData.Height then exit;
  1525. SC := BitmapData.GetScanline(ScanLineIndex);
  1526. MinWidth := BitmapData.Width;
  1527. if (Width > 0) and (Width < MinWidth) then
  1528. MinWidth := Width;
  1529. if InputFormat = BitmapData.PixelFormat then
  1530. begin
  1531. Move(PByte(InputData)[0], SC[0], BitmapData.BytesPerPixel * MinWidth);
  1532. end
  1533. else
  1534. begin
  1535. Buffer := GetMemory(MinWidth * SizeOf(TAlphaColor));
  1536. try
  1537. ScanlineToAlphaColor(InputData, Buffer, MinWidth, InputFormat);
  1538. AlphaColorToScanline(Buffer, SC, MinWidth, BitmapData.PixelFormat);
  1539. finally
  1540. FreeMemory(Buffer);
  1541. end;
  1542. end;
  1543. Result := True;
  1544. end;
  1545. {$ENDIF}
  1546. { TBitmapCodecWIC }
  1547. {$IFDEF MSWINDOWS}
  1548. function TBitmapCodecWIC.DecodeFrame(const Frame: IWICBitmapFrameDecode;
  1549. const Bitmap: TBitmapSurface; const MaxSizeLimit: Cardinal): Boolean;
  1550. type
  1551. TPrivateMethodType = function (const Frame: IWICBitmapFrameDecode;
  1552. const Bitmap: TBitmapSurface; const MaxSizeLimit: Cardinal): Boolean of object;
  1553. var
  1554. AMethod: TMethod;
  1555. AInvoke: TPrivateMethodType absolute AMethod;
  1556. begin
  1557. AMethod.Code := @TBitmapCodecWIC.DecodeFrame;
  1558. AMethod.Data := Self;
  1559. Result := AInvoke(Frame, Bitmap, MaxSizeLimit);
  1560. end;
  1561. class function TBitmapCodecWIC.GetImageSize(const AStream: TStream): TPointF;
  1562. var
  1563. Decoder: IWICBitmapDecoder;
  1564. Frame: IWICBitmapFrameDecode;
  1565. W, H: UINT;
  1566. CopyStream: TMemoryStream;
  1567. Stream: IWICStream;
  1568. SavePosition: Int64;
  1569. begin
  1570. W := 0;
  1571. H := 0;
  1572. SavePosition := AStream.Position;
  1573. try
  1574. CopyStream := TMemoryStream.Create;
  1575. try
  1576. CopyStream.CopyFrom(AStream, AStream.Size);
  1577. ImagingFactory.CreateStream(Stream);
  1578. Stream.InitializeFromMemory(CopyStream.Memory, CopyStream.Size);
  1579. ImagingFactory.CreateDecoderFromStream(stream, GUID_NULL, WICDecodeMetadataCacheOnDemand, Decoder);
  1580. if Decoder <> nil then
  1581. begin
  1582. Decoder.GetFrame(0, Frame);
  1583. if Frame <> nil then
  1584. Frame.GetSize(W, H);
  1585. end;
  1586. Result := PointF(W, H);
  1587. finally
  1588. CopyStream.Free;
  1589. end;
  1590. finally
  1591. AStream.Position := SavePosition;
  1592. end;
  1593. end;
  1594. function TBitmapCodecWIC.LoadThumbnailFromStream(const AStream: TStream;
  1595. const ASrc, ADest: TRectF; const UseEmbedded: Boolean;
  1596. const Bitmap: TBitmapSurface): Boolean;
  1597. var
  1598. Decoder: IWICBitmapDecoder;
  1599. CopyStream: TMemoryStream;
  1600. Stream: IWICStream;
  1601. Frame: IWICBitmapFrameDecode;
  1602. Bmp: IWICBitmapSource;
  1603. Converter: IWICFormatConverter;
  1604. Scaler: IWICBitmapScaler;
  1605. Clipper: IWICBitmapClipper;
  1606. Width, Height: UINT;
  1607. WRect: WICRect;
  1608. LResult: HRESULT;
  1609. begin
  1610. Result := False;
  1611. CopyStream := TMemoryStream.Create;
  1612. try
  1613. CopyStream.CopyFrom(AStream, AStream.Size);
  1614. ImagingFactory.CreateStream(Stream);
  1615. Stream.InitializeFromMemory(CopyStream.Memory, CopyStream.Size);
  1616. //kngstr
  1617. ImagingFactory.CreateDecoderFromStream(Stream, GUID_NULL, WICDecodeMetadataCacheOnDemand, Decoder);
  1618. if Decoder <> nil then begin
  1619. Decoder.GetFrame(0, Frame);
  1620. if UseEmbedded then
  1621. Frame.GetThumbnail(Bmp);
  1622. if Bmp <> nil then begin
  1623. ImagingFactory.CreateFormatConverter(Converter);
  1624. if Succeeded(Converter.Initialize(Bmp, GUID_WICPixelFormat32bppPBGRA, WICBitmapDitherTypeNone, nil, 0, 0)) then
  1625. begin
  1626. Converter.GetSize(Width, Height);
  1627. Bitmap.SetSize(Width, Height, TPixelFormat.BGRA);
  1628. Result := Succeeded(Converter.CopyPixels(nil, Bitmap.Pitch, Height * Cardinal(Bitmap.Pitch),
  1629. PByte(Bitmap.Bits)));
  1630. end;
  1631. end
  1632. else if Frame <> nil then begin
  1633. Frame.GetSize(Width, Height);
  1634. Clipper := nil;
  1635. if (not ASrc.IsEmpty) and (ASrc.Width < Width) and (ASrc.Height < Height) then begin
  1636. WRect.X := Trunc(ASrc.Left);
  1637. WRect.Y := Trunc(ASrc.Top);
  1638. WRect.Width := Trunc(ASrc.Width);
  1639. WRect.Height := Trunc(ASrc.Height);
  1640. // 剪裁
  1641. ImagingFactory.CreateBitmapClipper(Clipper);
  1642. if not Succeeded(Clipper.Initialize(frame, WRect)) then
  1643. Clipper := nil;
  1644. end;
  1645. LResult := S_FALSE;
  1646. // 缩放
  1647. ImagingFactory.CreateBitmapScaler(Scaler);
  1648. if (Clipper <> nil) then
  1649. LResult := Scaler.Initialize(Clipper, Trunc(ADest.Width), Trunc(ADest.Height), WICBitmapInterpolationModeLinear);
  1650. if not Succeeded(LResult) then
  1651. LResult := Scaler.Initialize(Frame, Trunc(ADest.Width), Trunc(ADest.Height), WICBitmapInterpolationModeLinear);
  1652. if Succeeded(LResult) then begin
  1653. ImagingFactory.CreateFormatConverter(Converter);
  1654. if Succeeded(Converter.Initialize(scaler, GUID_WICPixelFormat32bppPBGRA,
  1655. WICBitmapDitherTypeNone, nil, 0, 0)) then begin
  1656. Converter.GetSize(Width, Height);
  1657. Bitmap.SetSize(Width, Height, TPixelFormat.BGRA);
  1658. Result := Succeeded(Converter.CopyPixels(nil, Bitmap.Pitch, Height * Cardinal(Bitmap.Pitch),
  1659. PByte(Bitmap.Bits)));
  1660. end;
  1661. end;
  1662. end;
  1663. end;
  1664. finally
  1665. CopyStream.Free;
  1666. end;
  1667. end;
  1668. function TBitmapCodecWIC.LoadThumbnailFromStream(const AStream: TStream;
  1669. const AFitWidth, AFitHeight: Single; const UseEmbedded, AutoCut: Boolean;
  1670. const Bitmap: TBitmapSurface): Boolean;
  1671. var
  1672. Decoder: IWICBitmapDecoder;
  1673. CopyStream: TMemoryStream;
  1674. Stream: IWICStream;
  1675. Frame: IWICBitmapFrameDecode;
  1676. Bmp: IWICBitmapSource;
  1677. Converter: IWICFormatConverter;
  1678. Scaler: IWICBitmapScaler;
  1679. R: TRectF;
  1680. Width, Height: UINT;
  1681. begin
  1682. Result := False;
  1683. CopyStream := TMemoryStream.Create;
  1684. try
  1685. CopyStream.CopyFrom(AStream, AStream.Size);
  1686. ImagingFactory.CreateStream(Stream);
  1687. Stream.InitializeFromMemory(CopyStream.Memory, CopyStream.Size);
  1688. //kngstr
  1689. ImagingFactory.CreateDecoderFromStream(Stream, GUID_NULL, WICDecodeMetadataCacheOnDemand, Decoder);
  1690. if Decoder <> nil then
  1691. begin
  1692. Decoder.GetFrame(0, Frame);
  1693. if UseEmbedded then
  1694. Frame.GetThumbnail(Bmp);
  1695. if Bmp <> nil then
  1696. begin
  1697. ImagingFactory.CreateFormatConverter(Converter);
  1698. if Succeeded(Converter.Initialize(Bmp, GUID_WICPixelFormat32bppPBGRA, WICBitmapDitherTypeNone, nil, 0, 0)) then
  1699. begin
  1700. Converter.GetSize(Width, Height);
  1701. Bitmap.SetSize(Width, Height, TPixelFormat.BGRA);
  1702. Result := Succeeded(Converter.CopyPixels(nil, Bitmap.Pitch, Height * Cardinal(Bitmap.Pitch),
  1703. PByte(Bitmap.Bits)));
  1704. end;
  1705. end
  1706. else
  1707. if Frame <> nil then
  1708. begin
  1709. Frame.GetSize(Width, Height);
  1710. R := TRectF.Create(0, 0, Width, Height);
  1711. R.Fit(TRectF.Create(0, 0, AFitWidth, AFitHeight));
  1712. ImagingFactory.CreateBitmapScaler(Scaler);
  1713. if Succeeded(Scaler.Initialize(frame, Trunc(R.Width), Trunc(R.Height), WICBitmapInterpolationModeLinear)) then
  1714. begin
  1715. ImagingFactory.CreateFormatConverter(Converter);
  1716. if Succeeded(Converter.Initialize(scaler, GUID_WICPixelFormat32bppPBGRA,
  1717. WICBitmapDitherTypeNone, nil, 0, 0)) then
  1718. begin
  1719. Converter.GetSize(Width, Height);
  1720. Bitmap.SetSize(Width, Height, TPixelFormat.BGRA);
  1721. Result := Succeeded(Converter.CopyPixels(nil, Bitmap.Pitch, Height * Cardinal(Bitmap.Pitch),
  1722. PByte(Bitmap.Bits)));
  1723. end;
  1724. end;
  1725. end;
  1726. end;
  1727. finally
  1728. CopyStream.Free;
  1729. end;
  1730. end;
  1731. {$ENDIF}
  1732. end.