PngEncoder.java 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717
  1. package com.keypoint;
  2. import java.awt.Image;
  3. import java.awt.image.ImageObserver;
  4. import java.awt.image.PixelGrabber;
  5. import java.io.ByteArrayOutputStream;
  6. import java.io.IOException;
  7. import java.util.zip.CRC32;
  8. import java.util.zip.Deflater;
  9. import java.util.zip.DeflaterOutputStream;
  10. /**
  11. * PngEncoder takes a Java Image object and creates a byte string which can be
  12. * saved as a PNG file. The Image is presumed to use the DirectColorModel.
  13. *
  14. * <p>Thanks to Jay Denny at KeyPoint Software
  15. * http://www.keypoint.com/
  16. * who let me develop this code on company time.</p>
  17. *
  18. * <p>You may contact me with (probably very-much-needed) improvements,
  19. * comments, and bug fixes at:</p>
  20. *
  21. * <p><code>david@catcode.com</code></p>
  22. *
  23. * <p>This library is free software; you can redistribute it and/or
  24. * modify it under the terms of the GNU Lesser General Public
  25. * License as published by the Free Software Foundation; either
  26. * version 2.1 of the License, or (at your option) any later version.</p>
  27. *
  28. * <p>This library is distributed in the hope that it will be useful,
  29. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  30. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  31. * Lesser General Public License for more details.</p>
  32. *
  33. * <p>You should have received a copy of the GNU Lesser General Public
  34. * License along with this library; if not, write to the Free Software
  35. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
  36. * USA. A copy of the GNU LGPL may be found at
  37. * <code>http://www.gnu.org/copyleft/lesser.html</code></p>
  38. *
  39. * @author J. David Eisenberg
  40. * @version 1.5, 19 Oct 2003
  41. *
  42. * CHANGES:
  43. * --------
  44. * 19-Nov-2002 : CODING STYLE CHANGES ONLY (by David Gilbert for Object
  45. * Refinery Limited);
  46. * 19-Sep-2003 : Fix for platforms using EBCDIC (contributed by Paulo Soares);
  47. * 19-Oct-2003 : Change private fields to protected fields so that
  48. * PngEncoderB can inherit them (JDE)
  49. * Fixed bug with calculation of nRows
  50. * 15-Aug-2008 : Added scrunch.end() in writeImageData() method - see
  51. * JFreeChart bug report 2037930 (David Gilbert);
  52. */
  53. public class PngEncoder {
  54. /** Constant specifying that alpha channel should be encoded. */
  55. public static final boolean ENCODE_ALPHA = true;
  56. /** Constant specifying that alpha channel should not be encoded. */
  57. public static final boolean NO_ALPHA = false;
  58. /** Constants for filter (NONE). */
  59. public static final int FILTER_NONE = 0;
  60. /** Constants for filter (SUB). */
  61. public static final int FILTER_SUB = 1;
  62. /** Constants for filter (UP). */
  63. public static final int FILTER_UP = 2;
  64. /** Constants for filter (LAST). */
  65. public static final int FILTER_LAST = 2;
  66. /** IHDR tag. */
  67. protected static final byte[] IHDR = {73, 72, 68, 82};
  68. /** IDAT tag. */
  69. protected static final byte[] IDAT = {73, 68, 65, 84};
  70. /** IEND tag. */
  71. protected static final byte[] IEND = {73, 69, 78, 68};
  72. /** PHYS tag. */
  73. protected static final byte[] PHYS = {(byte)'p', (byte)'H', (byte)'Y',
  74. (byte)'s'};
  75. /** The png bytes. */
  76. protected byte[] pngBytes;
  77. /** The prior row. */
  78. protected byte[] priorRow;
  79. /** The left bytes. */
  80. protected byte[] leftBytes;
  81. /** The image. */
  82. protected Image image;
  83. /** The width. */
  84. protected int width;
  85. /** The height. */
  86. protected int height;
  87. /** The byte position. */
  88. protected int bytePos;
  89. /** The maximum position. */
  90. protected int maxPos;
  91. /** CRC. */
  92. protected CRC32 crc = new CRC32();
  93. /** The CRC value. */
  94. protected long crcValue;
  95. /** Encode alpha? */
  96. protected boolean encodeAlpha;
  97. /** The filter type. */
  98. protected int filter;
  99. /** The bytes-per-pixel. */
  100. protected int bytesPerPixel;
  101. /** The physical pixel dimension : number of pixels per inch on the X axis. */
  102. private int xDpi = 0;
  103. /** The physical pixel dimension : number of pixels per inch on the Y axis. */
  104. private int yDpi = 0;
  105. /** Used for conversion of DPI to Pixels per Meter. */
  106. static private float INCH_IN_METER_UNIT = 0.0254f;
  107. /**
  108. * The compression level (1 = best speed, 9 = best compression,
  109. * 0 = no compression).
  110. */
  111. protected int compressionLevel;
  112. /**
  113. * Class constructor.
  114. */
  115. public PngEncoder() {
  116. this(null, false, FILTER_NONE, 0);
  117. }
  118. /**
  119. * Class constructor specifying Image to encode, with no alpha channel
  120. * encoding.
  121. *
  122. * @param image A Java Image object which uses the DirectColorModel
  123. * @see java.awt.Image
  124. */
  125. public PngEncoder(Image image) {
  126. this(image, false, FILTER_NONE, 0);
  127. }
  128. /**
  129. * Class constructor specifying Image to encode, and whether to encode
  130. * alpha.
  131. *
  132. * @param image A Java Image object which uses the DirectColorModel
  133. * @param encodeAlpha Encode the alpha channel? false=no; true=yes
  134. * @see java.awt.Image
  135. */
  136. public PngEncoder(Image image, boolean encodeAlpha) {
  137. this(image, encodeAlpha, FILTER_NONE, 0);
  138. }
  139. /**
  140. * Class constructor specifying Image to encode, whether to encode alpha,
  141. * and filter to use.
  142. *
  143. * @param image A Java Image object which uses the DirectColorModel
  144. * @param encodeAlpha Encode the alpha channel? false=no; true=yes
  145. * @param whichFilter 0=none, 1=sub, 2=up
  146. * @see java.awt.Image
  147. */
  148. public PngEncoder(Image image, boolean encodeAlpha, int whichFilter) {
  149. this(image, encodeAlpha, whichFilter, 0);
  150. }
  151. /**
  152. * Class constructor specifying Image source to encode, whether to encode
  153. * alpha, filter to use, and compression level.
  154. *
  155. * @param image A Java Image object
  156. * @param encodeAlpha Encode the alpha channel? false=no; true=yes
  157. * @param whichFilter 0=none, 1=sub, 2=up
  158. * @param compLevel 0..9 (1 = best speed, 9 = best compression, 0 = no
  159. * compression)
  160. * @see java.awt.Image
  161. */
  162. public PngEncoder(Image image, boolean encodeAlpha, int whichFilter,
  163. int compLevel) {
  164. this.image = image;
  165. this.encodeAlpha = encodeAlpha;
  166. setFilter(whichFilter);
  167. if (compLevel >= 0 && compLevel <= 9) {
  168. this.compressionLevel = compLevel;
  169. }
  170. }
  171. /**
  172. * Set the image to be encoded.
  173. *
  174. * @param image A Java Image object which uses the DirectColorModel
  175. * @see java.awt.Image
  176. * @see java.awt.image.DirectColorModel
  177. */
  178. public void setImage(Image image) {
  179. this.image = image;
  180. this.pngBytes = null;
  181. }
  182. /**
  183. * Returns the image to be encoded.
  184. *
  185. * @return The image.
  186. */
  187. public Image getImage() {
  188. return this.image;
  189. }
  190. /**
  191. * Creates an array of bytes that is the PNG equivalent of the current
  192. * image, specifying whether to encode alpha or not.
  193. *
  194. * @param encodeAlpha boolean false=no alpha, true=encode alpha
  195. * @return an array of bytes, or null if there was a problem
  196. */
  197. public byte[] pngEncode(boolean encodeAlpha) {
  198. byte[] pngIdBytes = {-119, 80, 78, 71, 13, 10, 26, 10};
  199. if (this.image == null) {
  200. return null;
  201. }
  202. this.width = this.image.getWidth(null);
  203. this.height = this.image.getHeight(null);
  204. /*
  205. * start with an array that is big enough to hold all the pixels
  206. * (plus filter bytes), and an extra 200 bytes for header info
  207. */
  208. this.pngBytes = new byte[((this.width + 1) * this.height * 3) + 200];
  209. /*
  210. * keep track of largest byte written to the array
  211. */
  212. this.maxPos = 0;
  213. this.bytePos = writeBytes(pngIdBytes, 0);
  214. //hdrPos = bytePos;
  215. writeHeader();
  216. writeResolution();
  217. //dataPos = bytePos;
  218. if (writeImageData()) {
  219. writeEnd();
  220. this.pngBytes = resizeByteArray(this.pngBytes, this.maxPos);
  221. }
  222. else {
  223. this.pngBytes = null;
  224. }
  225. return this.pngBytes;
  226. }
  227. /**
  228. * Creates an array of bytes that is the PNG equivalent of the current
  229. * image. Alpha encoding is determined by its setting in the constructor.
  230. *
  231. * @return an array of bytes, or null if there was a problem
  232. */
  233. public byte[] pngEncode() {
  234. return pngEncode(this.encodeAlpha);
  235. }
  236. /**
  237. * Set the alpha encoding on or off.
  238. *
  239. * @param encodeAlpha false=no, true=yes
  240. */
  241. public void setEncodeAlpha(boolean encodeAlpha) {
  242. this.encodeAlpha = encodeAlpha;
  243. }
  244. /**
  245. * Retrieve alpha encoding status.
  246. *
  247. * @return boolean false=no, true=yes
  248. */
  249. public boolean getEncodeAlpha() {
  250. return this.encodeAlpha;
  251. }
  252. /**
  253. * Set the filter to use.
  254. *
  255. * @param whichFilter from constant list
  256. */
  257. public void setFilter(int whichFilter) {
  258. this.filter = FILTER_NONE;
  259. if (whichFilter <= FILTER_LAST) {
  260. this.filter = whichFilter;
  261. }
  262. }
  263. /**
  264. * Retrieve filtering scheme.
  265. *
  266. * @return int (see constant list)
  267. */
  268. public int getFilter() {
  269. return this.filter;
  270. }
  271. /**
  272. * Set the compression level to use.
  273. *
  274. * @param level the compression level (1 = best speed, 9 = best compression,
  275. * 0 = no compression)
  276. */
  277. public void setCompressionLevel(int level) {
  278. if (level >= 0 && level <= 9) {
  279. this.compressionLevel = level;
  280. }
  281. }
  282. /**
  283. * Retrieve compression level.
  284. *
  285. * @return int (1 = best speed, 9 = best compression, 0 = no compression)
  286. */
  287. public int getCompressionLevel() {
  288. return this.compressionLevel;
  289. }
  290. /**
  291. * Increase or decrease the length of a byte array.
  292. *
  293. * @param array The original array.
  294. * @param newLength The length you wish the new array to have.
  295. * @return Array of newly desired length. If shorter than the
  296. * original, the trailing elements are truncated.
  297. */
  298. protected byte[] resizeByteArray(byte[] array, int newLength) {
  299. byte[] newArray = new byte[newLength];
  300. int oldLength = array.length;
  301. System.arraycopy(array, 0, newArray, 0, Math.min(oldLength, newLength));
  302. return newArray;
  303. }
  304. /**
  305. * Write an array of bytes into the pngBytes array.
  306. * Note: This routine has the side effect of updating
  307. * maxPos, the largest element written in the array.
  308. * The array is resized by 1000 bytes or the length
  309. * of the data to be written, whichever is larger.
  310. *
  311. * @param data The data to be written into pngBytes.
  312. * @param offset The starting point to write to.
  313. * @return The next place to be written to in the pngBytes array.
  314. */
  315. protected int writeBytes(byte[] data, int offset) {
  316. this.maxPos = Math.max(this.maxPos, offset + data.length);
  317. if (data.length + offset > this.pngBytes.length) {
  318. this.pngBytes = resizeByteArray(this.pngBytes, this.pngBytes.length
  319. + Math.max(1000, data.length));
  320. }
  321. System.arraycopy(data, 0, this.pngBytes, offset, data.length);
  322. return offset + data.length;
  323. }
  324. /**
  325. * Write an array of bytes into the pngBytes array, specifying number of
  326. * bytes to write. Note: This routine has the side effect of updating
  327. * maxPos, the largest element written in the array.
  328. * The array is resized by 1000 bytes or the length
  329. * of the data to be written, whichever is larger.
  330. *
  331. * @param data The data to be written into pngBytes.
  332. * @param nBytes The number of bytes to be written.
  333. * @param offset The starting point to write to.
  334. * @return The next place to be written to in the pngBytes array.
  335. */
  336. protected int writeBytes(byte[] data, int nBytes, int offset) {
  337. this.maxPos = Math.max(this.maxPos, offset + nBytes);
  338. if (nBytes + offset > this.pngBytes.length) {
  339. this.pngBytes = resizeByteArray(this.pngBytes, this.pngBytes.length
  340. + Math.max(1000, nBytes));
  341. }
  342. System.arraycopy(data, 0, this.pngBytes, offset, nBytes);
  343. return offset + nBytes;
  344. }
  345. /**
  346. * Write a two-byte integer into the pngBytes array at a given position.
  347. *
  348. * @param n The integer to be written into pngBytes.
  349. * @param offset The starting point to write to.
  350. * @return The next place to be written to in the pngBytes array.
  351. */
  352. protected int writeInt2(int n, int offset) {
  353. byte[] temp = {(byte) ((n >> 8) & 0xff), (byte) (n & 0xff)};
  354. return writeBytes(temp, offset);
  355. }
  356. /**
  357. * Write a four-byte integer into the pngBytes array at a given position.
  358. *
  359. * @param n The integer to be written into pngBytes.
  360. * @param offset The starting point to write to.
  361. * @return The next place to be written to in the pngBytes array.
  362. */
  363. protected int writeInt4(int n, int offset) {
  364. byte[] temp = {(byte) ((n >> 24) & 0xff),
  365. (byte) ((n >> 16) & 0xff),
  366. (byte) ((n >> 8) & 0xff),
  367. (byte) (n & 0xff)};
  368. return writeBytes(temp, offset);
  369. }
  370. /**
  371. * Write a single byte into the pngBytes array at a given position.
  372. *
  373. * @param b The integer to be written into pngBytes.
  374. * @param offset The starting point to write to.
  375. * @return The next place to be written to in the pngBytes array.
  376. */
  377. protected int writeByte(int b, int offset) {
  378. byte[] temp = {(byte) b};
  379. return writeBytes(temp, offset);
  380. }
  381. /**
  382. * Write a PNG "IHDR" chunk into the pngBytes array.
  383. */
  384. protected void writeHeader() {
  385. int startPos = this.bytePos = writeInt4(13, this.bytePos);
  386. this.bytePos = writeBytes(IHDR, this.bytePos);
  387. this.width = this.image.getWidth(null);
  388. this.height = this.image.getHeight(null);
  389. this.bytePos = writeInt4(this.width, this.bytePos);
  390. this.bytePos = writeInt4(this.height, this.bytePos);
  391. this.bytePos = writeByte(8, this.bytePos); // bit depth
  392. this.bytePos = writeByte((this.encodeAlpha) ? 6 : 2, this.bytePos);
  393. // direct model
  394. this.bytePos = writeByte(0, this.bytePos); // compression method
  395. this.bytePos = writeByte(0, this.bytePos); // filter method
  396. this.bytePos = writeByte(0, this.bytePos); // no interlace
  397. this.crc.reset();
  398. this.crc.update(this.pngBytes, startPos, this.bytePos - startPos);
  399. this.crcValue = this.crc.getValue();
  400. this.bytePos = writeInt4((int) this.crcValue, this.bytePos);
  401. }
  402. /**
  403. * Perform "sub" filtering on the given row.
  404. * Uses temporary array leftBytes to store the original values
  405. * of the previous pixels. The array is 16 bytes long, which
  406. * will easily hold two-byte samples plus two-byte alpha.
  407. *
  408. * @param pixels The array holding the scan lines being built
  409. * @param startPos Starting position within pixels of bytes to be filtered.
  410. * @param width Width of a scanline in pixels.
  411. */
  412. protected void filterSub(byte[] pixels, int startPos, int width) {
  413. int offset = this.bytesPerPixel;
  414. int actualStart = startPos + offset;
  415. int nBytes = width * this.bytesPerPixel;
  416. int leftInsert = offset;
  417. int leftExtract = 0;
  418. for (int i = actualStart; i < startPos + nBytes; i++) {
  419. this.leftBytes[leftInsert] = pixels[i];
  420. pixels[i] = (byte) ((pixels[i] - this.leftBytes[leftExtract])
  421. % 256);
  422. leftInsert = (leftInsert + 1) % 0x0f;
  423. leftExtract = (leftExtract + 1) % 0x0f;
  424. }
  425. }
  426. /**
  427. * Perform "up" filtering on the given row.
  428. * Side effect: refills the prior row with current row
  429. *
  430. * @param pixels The array holding the scan lines being built
  431. * @param startPos Starting position within pixels of bytes to be filtered.
  432. * @param width Width of a scanline in pixels.
  433. */
  434. protected void filterUp(byte[] pixels, int startPos, int width) {
  435. final int nBytes = width * this.bytesPerPixel;
  436. for (int i = 0; i < nBytes; i++) {
  437. final byte currentByte = pixels[startPos + i];
  438. pixels[startPos + i] = (byte) ((pixels[startPos + i]
  439. - this.priorRow[i]) % 256);
  440. this.priorRow[i] = currentByte;
  441. }
  442. }
  443. /**
  444. * Write the image data into the pngBytes array.
  445. * This will write one or more PNG "IDAT" chunks. In order
  446. * to conserve memory, this method grabs as many rows as will
  447. * fit into 32K bytes, or the whole image; whichever is less.
  448. *
  449. *
  450. * @return true if no errors; false if error grabbing pixels
  451. */
  452. protected boolean writeImageData() {
  453. int rowsLeft = this.height; // number of rows remaining to write
  454. int startRow = 0; // starting row to process this time through
  455. int nRows; // how many rows to grab at a time
  456. byte[] scanLines; // the scan lines to be compressed
  457. int scanPos; // where we are in the scan lines
  458. int startPos; // where this line's actual pixels start (used
  459. // for filtering)
  460. byte[] compressedLines; // the resultant compressed lines
  461. int nCompressed; // how big is the compressed area?
  462. //int depth; // color depth ( handle only 8 or 32 )
  463. PixelGrabber pg;
  464. this.bytesPerPixel = (this.encodeAlpha) ? 4 : 3;
  465. Deflater scrunch = new Deflater(this.compressionLevel);
  466. ByteArrayOutputStream outBytes = new ByteArrayOutputStream(1024);
  467. DeflaterOutputStream compBytes = new DeflaterOutputStream(outBytes,
  468. scrunch);
  469. try {
  470. while (rowsLeft > 0) {
  471. nRows = Math.min(32767 / (this.width
  472. * (this.bytesPerPixel + 1)), rowsLeft);
  473. nRows = Math.max(nRows, 1);
  474. int[] pixels = new int[this.width * nRows];
  475. pg = new PixelGrabber(this.image, 0, startRow,
  476. this.width, nRows, pixels, 0, this.width);
  477. try {
  478. pg.grabPixels();
  479. }
  480. catch (Exception e) {
  481. System.err.println("interrupted waiting for pixels!");
  482. return false;
  483. }
  484. if ((pg.getStatus() & ImageObserver.ABORT) != 0) {
  485. System.err.println("image fetch aborted or errored");
  486. return false;
  487. }
  488. /*
  489. * Create a data chunk. scanLines adds "nRows" for
  490. * the filter bytes.
  491. */
  492. scanLines = new byte[this.width * nRows * this.bytesPerPixel
  493. + nRows];
  494. if (this.filter == FILTER_SUB) {
  495. this.leftBytes = new byte[16];
  496. }
  497. if (this.filter == FILTER_UP) {
  498. this.priorRow = new byte[this.width * this.bytesPerPixel];
  499. }
  500. scanPos = 0;
  501. startPos = 1;
  502. for (int i = 0; i < this.width * nRows; i++) {
  503. if (i % this.width == 0) {
  504. scanLines[scanPos++] = (byte) this.filter;
  505. startPos = scanPos;
  506. }
  507. scanLines[scanPos++] = (byte) ((pixels[i] >> 16) & 0xff);
  508. scanLines[scanPos++] = (byte) ((pixels[i] >> 8) & 0xff);
  509. scanLines[scanPos++] = (byte) ((pixels[i]) & 0xff);
  510. if (this.encodeAlpha) {
  511. scanLines[scanPos++] = (byte) ((pixels[i] >> 24)
  512. & 0xff);
  513. }
  514. if ((i % this.width == this.width - 1)
  515. && (this.filter != FILTER_NONE)) {
  516. if (this.filter == FILTER_SUB) {
  517. filterSub(scanLines, startPos, this.width);
  518. }
  519. if (this.filter == FILTER_UP) {
  520. filterUp(scanLines, startPos, this.width);
  521. }
  522. }
  523. }
  524. /*
  525. * Write these lines to the output area
  526. */
  527. compBytes.write(scanLines, 0, scanPos);
  528. startRow += nRows;
  529. rowsLeft -= nRows;
  530. }
  531. compBytes.close();
  532. /*
  533. * Write the compressed bytes
  534. */
  535. compressedLines = outBytes.toByteArray();
  536. nCompressed = compressedLines.length;
  537. this.crc.reset();
  538. this.bytePos = writeInt4(nCompressed, this.bytePos);
  539. this.bytePos = writeBytes(IDAT, this.bytePos);
  540. this.crc.update(IDAT);
  541. this.bytePos = writeBytes(compressedLines, nCompressed,
  542. this.bytePos);
  543. this.crc.update(compressedLines, 0, nCompressed);
  544. this.crcValue = this.crc.getValue();
  545. this.bytePos = writeInt4((int) this.crcValue, this.bytePos);
  546. scrunch.finish();
  547. scrunch.end();
  548. return true;
  549. }
  550. catch (IOException e) {
  551. System.err.println(e.toString());
  552. return false;
  553. }
  554. }
  555. /**
  556. * Write a PNG "IEND" chunk into the pngBytes array.
  557. */
  558. protected void writeEnd() {
  559. this.bytePos = writeInt4(0, this.bytePos);
  560. this.bytePos = writeBytes(IEND, this.bytePos);
  561. this.crc.reset();
  562. this.crc.update(IEND);
  563. this.crcValue = this.crc.getValue();
  564. this.bytePos = writeInt4((int) this.crcValue, this.bytePos);
  565. }
  566. /**
  567. * Set the DPI for the X axis.
  568. *
  569. * @param xDpi The number of dots per inch
  570. */
  571. public void setXDpi(int xDpi) {
  572. this.xDpi = Math.round(xDpi / INCH_IN_METER_UNIT);
  573. }
  574. /**
  575. * Get the DPI for the X axis.
  576. *
  577. * @return The number of dots per inch
  578. */
  579. public int getXDpi() {
  580. return Math.round(this.xDpi * INCH_IN_METER_UNIT);
  581. }
  582. /**
  583. * Set the DPI for the Y axis.
  584. *
  585. * @param yDpi The number of dots per inch
  586. */
  587. public void setYDpi(int yDpi) {
  588. this.yDpi = Math.round(yDpi / INCH_IN_METER_UNIT);
  589. }
  590. /**
  591. * Get the DPI for the Y axis.
  592. *
  593. * @return The number of dots per inch
  594. */
  595. public int getYDpi() {
  596. return Math.round(this.yDpi * INCH_IN_METER_UNIT);
  597. }
  598. /**
  599. * Set the DPI resolution.
  600. *
  601. * @param xDpi The number of dots per inch for the X axis.
  602. * @param yDpi The number of dots per inch for the Y axis.
  603. */
  604. public void setDpi(int xDpi, int yDpi) {
  605. this.xDpi = Math.round(xDpi / INCH_IN_METER_UNIT);
  606. this.yDpi = Math.round(yDpi / INCH_IN_METER_UNIT);
  607. }
  608. /**
  609. * Write a PNG "pHYs" chunk into the pngBytes array.
  610. */
  611. protected void writeResolution() {
  612. if (this.xDpi > 0 && this.yDpi > 0) {
  613. final int startPos = this.bytePos = writeInt4(9, this.bytePos);
  614. this.bytePos = writeBytes(PHYS, this.bytePos);
  615. this.bytePos = writeInt4(this.xDpi, this.bytePos);
  616. this.bytePos = writeInt4(this.yDpi, this.bytePos);
  617. this.bytePos = writeByte(1, this.bytePos); // unit is the meter.
  618. this.crc.reset();
  619. this.crc.update(this.pngBytes, startPos, this.bytePos - startPos);
  620. this.crcValue = this.crc.getValue();
  621. this.bytePos = writeInt4((int) this.crcValue, this.bytePos);
  622. }
  623. }
  624. }