ksBitmapHelper.pas 63 KB

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