blob: b1a548ea809e3b79c02104a334dae65477a751b4 [file] [log] [blame]
Adam Lesinski282e1812014-01-23 18:17:42 -08001//
2// Copyright 2006 The Android Open Source Project
3//
4// Build resource files from raw assets.
5//
6
7#define PNG_INTERNAL
8
9#include "Images.h"
10
11#include <androidfw/ResourceTypes.h>
12#include <utils/ByteOrder.h>
13
14#include <png.h>
15#include <zlib.h>
16
17#define NOISY(x) //x
18
19static void
20png_write_aapt_file(png_structp png_ptr, png_bytep data, png_size_t length)
21{
22 AaptFile* aaptfile = (AaptFile*) png_get_io_ptr(png_ptr);
23 status_t err = aaptfile->writeData(data, length);
24 if (err != NO_ERROR) {
25 png_error(png_ptr, "Write Error");
26 }
27}
28
29
30static void
31png_flush_aapt_file(png_structp png_ptr)
32{
33}
34
35// This holds an image as 8bpp RGBA.
36struct image_info
37{
38 image_info() : rows(NULL), is9Patch(false), allocRows(NULL) { }
39 ~image_info() {
40 if (rows && rows != allocRows) {
41 free(rows);
42 }
43 if (allocRows) {
44 for (int i=0; i<(int)allocHeight; i++) {
45 free(allocRows[i]);
46 }
47 free(allocRows);
48 }
49 free(info9Patch.xDivs);
50 free(info9Patch.yDivs);
51 free(info9Patch.colors);
52 }
53
54 png_uint_32 width;
55 png_uint_32 height;
56 png_bytepp rows;
57
58 // 9-patch info.
59 bool is9Patch;
60 Res_png_9patch info9Patch;
61
62 // Layout padding, if relevant
63 bool haveLayoutBounds;
64 int32_t layoutBoundsLeft;
65 int32_t layoutBoundsTop;
66 int32_t layoutBoundsRight;
67 int32_t layoutBoundsBottom;
68
69 png_uint_32 allocHeight;
70 png_bytepp allocRows;
71};
72
John Reck859e19f2013-09-05 16:26:04 -070073static void log_warning(png_structp png_ptr, png_const_charp warning_message)
74{
75 const char* imageName = (const char*) png_get_error_ptr(png_ptr);
76 fprintf(stderr, "%s: libpng warning: %s\n", imageName, warning_message);
77}
78
Adam Lesinski282e1812014-01-23 18:17:42 -080079static void read_png(const char* imageName,
80 png_structp read_ptr, png_infop read_info,
81 image_info* outImageInfo)
82{
83 int color_type;
84 int bit_depth, interlace_type, compression_type;
85 int i;
86
John Reck859e19f2013-09-05 16:26:04 -070087 png_set_error_fn(read_ptr, const_cast<char*>(imageName),
88 NULL /* use default errorfn */, log_warning);
Adam Lesinski282e1812014-01-23 18:17:42 -080089 png_read_info(read_ptr, read_info);
90
91 png_get_IHDR(read_ptr, read_info, &outImageInfo->width,
92 &outImageInfo->height, &bit_depth, &color_type,
93 &interlace_type, &compression_type, NULL);
94
95 //printf("Image %s:\n", imageName);
96 //printf("color_type=%d, bit_depth=%d, interlace_type=%d, compression_type=%d\n",
97 // color_type, bit_depth, interlace_type, compression_type);
98
99 if (color_type == PNG_COLOR_TYPE_PALETTE)
100 png_set_palette_to_rgb(read_ptr);
101
102 if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8)
103 png_set_expand_gray_1_2_4_to_8(read_ptr);
104
105 if (png_get_valid(read_ptr, read_info, PNG_INFO_tRNS)) {
106 //printf("Has PNG_INFO_tRNS!\n");
107 png_set_tRNS_to_alpha(read_ptr);
108 }
109
110 if (bit_depth == 16)
111 png_set_strip_16(read_ptr);
112
113 if ((color_type&PNG_COLOR_MASK_ALPHA) == 0)
114 png_set_add_alpha(read_ptr, 0xFF, PNG_FILLER_AFTER);
115
116 if (color_type == PNG_COLOR_TYPE_GRAY || color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
117 png_set_gray_to_rgb(read_ptr);
118
John Reck859e19f2013-09-05 16:26:04 -0700119 png_set_interlace_handling(read_ptr);
120
Adam Lesinski282e1812014-01-23 18:17:42 -0800121 png_read_update_info(read_ptr, read_info);
122
123 outImageInfo->rows = (png_bytepp)malloc(
124 outImageInfo->height * sizeof(png_bytep));
125 outImageInfo->allocHeight = outImageInfo->height;
126 outImageInfo->allocRows = outImageInfo->rows;
127
128 png_set_rows(read_ptr, read_info, outImageInfo->rows);
129
130 for (i = 0; i < (int)outImageInfo->height; i++)
131 {
132 outImageInfo->rows[i] = (png_bytep)
133 malloc(png_get_rowbytes(read_ptr, read_info));
134 }
135
136 png_read_image(read_ptr, outImageInfo->rows);
137
138 png_read_end(read_ptr, read_info);
139
140 NOISY(printf("Image %s: w=%d, h=%d, d=%d, colors=%d, inter=%d, comp=%d\n",
141 imageName,
142 (int)outImageInfo->width, (int)outImageInfo->height,
143 bit_depth, color_type,
144 interlace_type, compression_type));
145
146 png_get_IHDR(read_ptr, read_info, &outImageInfo->width,
147 &outImageInfo->height, &bit_depth, &color_type,
148 &interlace_type, &compression_type, NULL);
149}
150
151#define COLOR_TRANSPARENT 0
152#define COLOR_WHITE 0xFFFFFFFF
153#define COLOR_TICK 0xFF000000
154#define COLOR_LAYOUT_BOUNDS_TICK 0xFF0000FF
155
156enum {
157 TICK_TYPE_NONE,
158 TICK_TYPE_TICK,
159 TICK_TYPE_LAYOUT_BOUNDS,
160 TICK_TYPE_BOTH
161};
162
163static int tick_type(png_bytep p, bool transparent, const char** outError)
164{
165 png_uint_32 color = p[0] | (p[1] << 8) | (p[2] << 16) | (p[3] << 24);
166
167 if (transparent) {
168 if (p[3] == 0) {
169 return TICK_TYPE_NONE;
170 }
171 if (color == COLOR_LAYOUT_BOUNDS_TICK) {
172 return TICK_TYPE_LAYOUT_BOUNDS;
173 }
174 if (color == COLOR_TICK) {
175 return TICK_TYPE_TICK;
176 }
177
178 // Error cases
179 if (p[3] != 0xff) {
180 *outError = "Frame pixels must be either solid or transparent (not intermediate alphas)";
181 return TICK_TYPE_NONE;
182 }
183 if (p[0] != 0 || p[1] != 0 || p[2] != 0) {
184 *outError = "Ticks in transparent frame must be black or red";
185 }
186 return TICK_TYPE_TICK;
187 }
188
189 if (p[3] != 0xFF) {
190 *outError = "White frame must be a solid color (no alpha)";
191 }
192 if (color == COLOR_WHITE) {
193 return TICK_TYPE_NONE;
194 }
195 if (color == COLOR_TICK) {
196 return TICK_TYPE_TICK;
197 }
198 if (color == COLOR_LAYOUT_BOUNDS_TICK) {
199 return TICK_TYPE_LAYOUT_BOUNDS;
200 }
201
202 if (p[0] != 0 || p[1] != 0 || p[2] != 0) {
203 *outError = "Ticks in white frame must be black or red";
204 return TICK_TYPE_NONE;
205 }
206 return TICK_TYPE_TICK;
207}
208
209enum {
210 TICK_START,
211 TICK_INSIDE_1,
212 TICK_OUTSIDE_1
213};
214
215static status_t get_horizontal_ticks(
216 png_bytep row, int width, bool transparent, bool required,
217 int32_t* outLeft, int32_t* outRight, const char** outError,
218 uint8_t* outDivs, bool multipleAllowed)
219{
220 int i;
221 *outLeft = *outRight = -1;
222 int state = TICK_START;
223 bool found = false;
224
225 for (i=1; i<width-1; i++) {
226 if (TICK_TYPE_TICK == tick_type(row+i*4, transparent, outError)) {
227 if (state == TICK_START ||
228 (state == TICK_OUTSIDE_1 && multipleAllowed)) {
229 *outLeft = i-1;
230 *outRight = width-2;
231 found = true;
232 if (outDivs != NULL) {
233 *outDivs += 2;
234 }
235 state = TICK_INSIDE_1;
236 } else if (state == TICK_OUTSIDE_1) {
237 *outError = "Can't have more than one marked region along edge";
238 *outLeft = i;
239 return UNKNOWN_ERROR;
240 }
241 } else if (*outError == NULL) {
242 if (state == TICK_INSIDE_1) {
243 // We're done with this div. Move on to the next.
244 *outRight = i-1;
245 outRight += 2;
246 outLeft += 2;
247 state = TICK_OUTSIDE_1;
248 }
249 } else {
250 *outLeft = i;
251 return UNKNOWN_ERROR;
252 }
253 }
254
255 if (required && !found) {
256 *outError = "No marked region found along edge";
257 *outLeft = -1;
258 return UNKNOWN_ERROR;
259 }
260
261 return NO_ERROR;
262}
263
264static status_t get_vertical_ticks(
265 png_bytepp rows, int offset, int height, bool transparent, bool required,
266 int32_t* outTop, int32_t* outBottom, const char** outError,
267 uint8_t* outDivs, bool multipleAllowed)
268{
269 int i;
270 *outTop = *outBottom = -1;
271 int state = TICK_START;
272 bool found = false;
273
274 for (i=1; i<height-1; i++) {
275 if (TICK_TYPE_TICK == tick_type(rows[i]+offset, transparent, outError)) {
276 if (state == TICK_START ||
277 (state == TICK_OUTSIDE_1 && multipleAllowed)) {
278 *outTop = i-1;
279 *outBottom = height-2;
280 found = true;
281 if (outDivs != NULL) {
282 *outDivs += 2;
283 }
284 state = TICK_INSIDE_1;
285 } else if (state == TICK_OUTSIDE_1) {
286 *outError = "Can't have more than one marked region along edge";
287 *outTop = i;
288 return UNKNOWN_ERROR;
289 }
290 } else if (*outError == NULL) {
291 if (state == TICK_INSIDE_1) {
292 // We're done with this div. Move on to the next.
293 *outBottom = i-1;
294 outTop += 2;
295 outBottom += 2;
296 state = TICK_OUTSIDE_1;
297 }
298 } else {
299 *outTop = i;
300 return UNKNOWN_ERROR;
301 }
302 }
303
304 if (required && !found) {
305 *outError = "No marked region found along edge";
306 *outTop = -1;
307 return UNKNOWN_ERROR;
308 }
309
310 return NO_ERROR;
311}
312
313static status_t get_horizontal_layout_bounds_ticks(
314 png_bytep row, int width, bool transparent, bool required,
315 int32_t* outLeft, int32_t* outRight, const char** outError)
316{
317 int i;
318 *outLeft = *outRight = 0;
319
320 // Look for left tick
321 if (TICK_TYPE_LAYOUT_BOUNDS == tick_type(row + 4, transparent, outError)) {
322 // Starting with a layout padding tick
323 i = 1;
324 while (i < width - 1) {
325 (*outLeft)++;
326 i++;
327 int tick = tick_type(row + i * 4, transparent, outError);
328 if (tick != TICK_TYPE_LAYOUT_BOUNDS) {
329 break;
330 }
331 }
332 }
333
334 // Look for right tick
335 if (TICK_TYPE_LAYOUT_BOUNDS == tick_type(row + (width - 2) * 4, transparent, outError)) {
336 // Ending with a layout padding tick
337 i = width - 2;
338 while (i > 1) {
339 (*outRight)++;
340 i--;
341 int tick = tick_type(row+i*4, transparent, outError);
342 if (tick != TICK_TYPE_LAYOUT_BOUNDS) {
343 break;
344 }
345 }
346 }
347
348 return NO_ERROR;
349}
350
351static status_t get_vertical_layout_bounds_ticks(
352 png_bytepp rows, int offset, int height, bool transparent, bool required,
353 int32_t* outTop, int32_t* outBottom, const char** outError)
354{
355 int i;
356 *outTop = *outBottom = 0;
357
358 // Look for top tick
359 if (TICK_TYPE_LAYOUT_BOUNDS == tick_type(rows[1] + offset, transparent, outError)) {
360 // Starting with a layout padding tick
361 i = 1;
362 while (i < height - 1) {
363 (*outTop)++;
364 i++;
365 int tick = tick_type(rows[i] + offset, transparent, outError);
366 if (tick != TICK_TYPE_LAYOUT_BOUNDS) {
367 break;
368 }
369 }
370 }
371
372 // Look for bottom tick
373 if (TICK_TYPE_LAYOUT_BOUNDS == tick_type(rows[height - 2] + offset, transparent, outError)) {
374 // Ending with a layout padding tick
375 i = height - 2;
376 while (i > 1) {
377 (*outBottom)++;
378 i--;
379 int tick = tick_type(rows[i] + offset, transparent, outError);
380 if (tick != TICK_TYPE_LAYOUT_BOUNDS) {
381 break;
382 }
383 }
384 }
385
386 return NO_ERROR;
387}
388
389
390static uint32_t get_color(
391 png_bytepp rows, int left, int top, int right, int bottom)
392{
393 png_bytep color = rows[top] + left*4;
394
395 if (left > right || top > bottom) {
396 return Res_png_9patch::TRANSPARENT_COLOR;
397 }
398
399 while (top <= bottom) {
400 for (int i = left; i <= right; i++) {
401 png_bytep p = rows[top]+i*4;
402 if (color[3] == 0) {
403 if (p[3] != 0) {
404 return Res_png_9patch::NO_COLOR;
405 }
406 } else if (p[0] != color[0] || p[1] != color[1]
407 || p[2] != color[2] || p[3] != color[3]) {
408 return Res_png_9patch::NO_COLOR;
409 }
410 }
411 top++;
412 }
413
414 if (color[3] == 0) {
415 return Res_png_9patch::TRANSPARENT_COLOR;
416 }
417 return (color[3]<<24) | (color[0]<<16) | (color[1]<<8) | color[2];
418}
419
420static void select_patch(
421 int which, int front, int back, int size, int* start, int* end)
422{
423 switch (which) {
424 case 0:
425 *start = 0;
426 *end = front-1;
427 break;
428 case 1:
429 *start = front;
430 *end = back-1;
431 break;
432 case 2:
433 *start = back;
434 *end = size-1;
435 break;
436 }
437}
438
439static uint32_t get_color(image_info* image, int hpatch, int vpatch)
440{
441 int left, right, top, bottom;
442 select_patch(
443 hpatch, image->info9Patch.xDivs[0], image->info9Patch.xDivs[1],
444 image->width, &left, &right);
445 select_patch(
446 vpatch, image->info9Patch.yDivs[0], image->info9Patch.yDivs[1],
447 image->height, &top, &bottom);
448 //printf("Selecting h=%d v=%d: (%d,%d)-(%d,%d)\n",
449 // hpatch, vpatch, left, top, right, bottom);
450 const uint32_t c = get_color(image->rows, left, top, right, bottom);
451 NOISY(printf("Color in (%d,%d)-(%d,%d): #%08x\n", left, top, right, bottom, c));
452 return c;
453}
454
455static status_t do_9patch(const char* imageName, image_info* image)
456{
457 image->is9Patch = true;
458
459 int W = image->width;
460 int H = image->height;
461 int i, j;
462
463 int maxSizeXDivs = W * sizeof(int32_t);
464 int maxSizeYDivs = H * sizeof(int32_t);
Elliott Hughesb30296b2013-10-29 15:25:52 -0700465 int32_t* xDivs = image->info9Patch.xDivs = (int32_t*) malloc(maxSizeXDivs);
466 int32_t* yDivs = image->info9Patch.yDivs = (int32_t*) malloc(maxSizeYDivs);
Adam Lesinski282e1812014-01-23 18:17:42 -0800467 uint8_t numXDivs = 0;
468 uint8_t numYDivs = 0;
469 int8_t numColors;
470 int numRows;
471 int numCols;
472 int top;
473 int left;
474 int right;
475 int bottom;
476 memset(xDivs, -1, maxSizeXDivs);
477 memset(yDivs, -1, maxSizeYDivs);
478 image->info9Patch.paddingLeft = image->info9Patch.paddingRight =
479 image->info9Patch.paddingTop = image->info9Patch.paddingBottom = -1;
480
481 image->layoutBoundsLeft = image->layoutBoundsRight =
482 image->layoutBoundsTop = image->layoutBoundsBottom = 0;
483
484 png_bytep p = image->rows[0];
485 bool transparent = p[3] == 0;
486 bool hasColor = false;
487
488 const char* errorMsg = NULL;
489 int errorPixel = -1;
490 const char* errorEdge = NULL;
491
492 int colorIndex = 0;
493
494 // Validate size...
495 if (W < 3 || H < 3) {
496 errorMsg = "Image must be at least 3x3 (1x1 without frame) pixels";
497 goto getout;
498 }
499
500 // Validate frame...
501 if (!transparent &&
502 (p[0] != 0xFF || p[1] != 0xFF || p[2] != 0xFF || p[3] != 0xFF)) {
503 errorMsg = "Must have one-pixel frame that is either transparent or white";
504 goto getout;
505 }
506
507 // Find left and right of sizing areas...
508 if (get_horizontal_ticks(p, W, transparent, true, &xDivs[0],
509 &xDivs[1], &errorMsg, &numXDivs, true) != NO_ERROR) {
510 errorPixel = xDivs[0];
511 errorEdge = "top";
512 goto getout;
513 }
514
515 // Find top and bottom of sizing areas...
516 if (get_vertical_ticks(image->rows, 0, H, transparent, true, &yDivs[0],
517 &yDivs[1], &errorMsg, &numYDivs, true) != NO_ERROR) {
518 errorPixel = yDivs[0];
519 errorEdge = "left";
520 goto getout;
521 }
522
Elliott Hughesb30296b2013-10-29 15:25:52 -0700523 // Copy patch size data into image...
524 image->info9Patch.numXDivs = numXDivs;
525 image->info9Patch.numYDivs = numYDivs;
526
Adam Lesinski282e1812014-01-23 18:17:42 -0800527 // Find left and right of padding area...
528 if (get_horizontal_ticks(image->rows[H-1], W, transparent, false, &image->info9Patch.paddingLeft,
529 &image->info9Patch.paddingRight, &errorMsg, NULL, false) != NO_ERROR) {
530 errorPixel = image->info9Patch.paddingLeft;
531 errorEdge = "bottom";
532 goto getout;
533 }
534
535 // Find top and bottom of padding area...
536 if (get_vertical_ticks(image->rows, (W-1)*4, H, transparent, false, &image->info9Patch.paddingTop,
537 &image->info9Patch.paddingBottom, &errorMsg, NULL, false) != NO_ERROR) {
538 errorPixel = image->info9Patch.paddingTop;
539 errorEdge = "right";
540 goto getout;
541 }
542
543 // Find left and right of layout padding...
544 get_horizontal_layout_bounds_ticks(image->rows[H-1], W, transparent, false,
545 &image->layoutBoundsLeft,
546 &image->layoutBoundsRight, &errorMsg);
547
548 get_vertical_layout_bounds_ticks(image->rows, (W-1)*4, H, transparent, false,
549 &image->layoutBoundsTop,
550 &image->layoutBoundsBottom, &errorMsg);
551
552 image->haveLayoutBounds = image->layoutBoundsLeft != 0
553 || image->layoutBoundsRight != 0
554 || image->layoutBoundsTop != 0
555 || image->layoutBoundsBottom != 0;
556
557 if (image->haveLayoutBounds) {
558 NOISY(printf("layoutBounds=%d %d %d %d\n", image->layoutBoundsLeft, image->layoutBoundsTop,
559 image->layoutBoundsRight, image->layoutBoundsBottom));
560 }
561
Adam Lesinski282e1812014-01-23 18:17:42 -0800562 // If padding is not yet specified, take values from size.
563 if (image->info9Patch.paddingLeft < 0) {
564 image->info9Patch.paddingLeft = xDivs[0];
565 image->info9Patch.paddingRight = W - 2 - xDivs[1];
566 } else {
567 // Adjust value to be correct!
568 image->info9Patch.paddingRight = W - 2 - image->info9Patch.paddingRight;
569 }
570 if (image->info9Patch.paddingTop < 0) {
571 image->info9Patch.paddingTop = yDivs[0];
572 image->info9Patch.paddingBottom = H - 2 - yDivs[1];
573 } else {
574 // Adjust value to be correct!
575 image->info9Patch.paddingBottom = H - 2 - image->info9Patch.paddingBottom;
576 }
577
578 NOISY(printf("Size ticks for %s: x0=%d, x1=%d, y0=%d, y1=%d\n", imageName,
579 image->info9Patch.xDivs[0], image->info9Patch.xDivs[1],
580 image->info9Patch.yDivs[0], image->info9Patch.yDivs[1]));
581 NOISY(printf("padding ticks for %s: l=%d, r=%d, t=%d, b=%d\n", imageName,
582 image->info9Patch.paddingLeft, image->info9Patch.paddingRight,
583 image->info9Patch.paddingTop, image->info9Patch.paddingBottom));
584
585 // Remove frame from image.
586 image->rows = (png_bytepp)malloc((H-2) * sizeof(png_bytep));
587 for (i=0; i<(H-2); i++) {
588 image->rows[i] = image->allocRows[i+1];
589 memmove(image->rows[i], image->rows[i]+4, (W-2)*4);
590 }
591 image->width -= 2;
592 W = image->width;
593 image->height -= 2;
594 H = image->height;
595
596 // Figure out the number of rows and columns in the N-patch
597 numCols = numXDivs + 1;
598 if (xDivs[0] == 0) { // Column 1 is strechable
599 numCols--;
600 }
601 if (xDivs[numXDivs - 1] == W) {
602 numCols--;
603 }
604 numRows = numYDivs + 1;
605 if (yDivs[0] == 0) { // Row 1 is strechable
606 numRows--;
607 }
608 if (yDivs[numYDivs - 1] == H) {
609 numRows--;
610 }
611
612 // Make sure the amount of rows and columns will fit in the number of
613 // colors we can use in the 9-patch format.
614 if (numRows * numCols > 0x7F) {
615 errorMsg = "Too many rows and columns in 9-patch perimeter";
616 goto getout;
617 }
618
619 numColors = numRows * numCols;
620 image->info9Patch.numColors = numColors;
621 image->info9Patch.colors = (uint32_t*)malloc(numColors * sizeof(uint32_t));
622
623 // Fill in color information for each patch.
624
625 uint32_t c;
626 top = 0;
627
628 // The first row always starts with the top being at y=0 and the bottom
629 // being either yDivs[1] (if yDivs[0]=0) of yDivs[0]. In the former case
630 // the first row is stretchable along the Y axis, otherwise it is fixed.
631 // The last row always ends with the bottom being bitmap.height and the top
632 // being either yDivs[numYDivs-2] (if yDivs[numYDivs-1]=bitmap.height) or
633 // yDivs[numYDivs-1]. In the former case the last row is stretchable along
634 // the Y axis, otherwise it is fixed.
635 //
636 // The first and last columns are similarly treated with respect to the X
637 // axis.
638 //
639 // The above is to help explain some of the special casing that goes on the
640 // code below.
641
642 // The initial yDiv and whether the first row is considered stretchable or
643 // not depends on whether yDiv[0] was zero or not.
644 for (j = (yDivs[0] == 0 ? 1 : 0);
645 j <= numYDivs && top < H;
646 j++) {
647 if (j == numYDivs) {
648 bottom = H;
649 } else {
650 bottom = yDivs[j];
651 }
652 left = 0;
653 // The initial xDiv and whether the first column is considered
654 // stretchable or not depends on whether xDiv[0] was zero or not.
655 for (i = xDivs[0] == 0 ? 1 : 0;
656 i <= numXDivs && left < W;
657 i++) {
658 if (i == numXDivs) {
659 right = W;
660 } else {
661 right = xDivs[i];
662 }
663 c = get_color(image->rows, left, top, right - 1, bottom - 1);
664 image->info9Patch.colors[colorIndex++] = c;
665 NOISY(if (c != Res_png_9patch::NO_COLOR) hasColor = true);
666 left = right;
667 }
668 top = bottom;
669 }
670
671 assert(colorIndex == numColors);
672
673 for (i=0; i<numColors; i++) {
674 if (hasColor) {
675 if (i == 0) printf("Colors in %s:\n ", imageName);
676 printf(" #%08x", image->info9Patch.colors[i]);
677 if (i == numColors - 1) printf("\n");
678 }
679 }
680
681 image->is9Patch = true;
682 image->info9Patch.deviceToFile();
683
684getout:
685 if (errorMsg) {
686 fprintf(stderr,
687 "ERROR: 9-patch image %s malformed.\n"
688 " %s.\n", imageName, errorMsg);
689 if (errorEdge != NULL) {
690 if (errorPixel >= 0) {
691 fprintf(stderr,
692 " Found at pixel #%d along %s edge.\n", errorPixel, errorEdge);
693 } else {
694 fprintf(stderr,
695 " Found along %s edge.\n", errorEdge);
696 }
697 }
698 return UNKNOWN_ERROR;
699 }
700 return NO_ERROR;
701}
702
703static void checkNinePatchSerialization(Res_png_9patch* inPatch, void * data)
704{
705 if (sizeof(void*) != sizeof(int32_t)) {
706 // can't deserialize on a non-32 bit system
707 return;
708 }
709 size_t patchSize = inPatch->serializedSize();
710 void * newData = malloc(patchSize);
711 memcpy(newData, data, patchSize);
712 Res_png_9patch* outPatch = inPatch->deserialize(newData);
713 // deserialization is done in place, so outPatch == newData
714 assert(outPatch == newData);
715 assert(outPatch->numXDivs == inPatch->numXDivs);
716 assert(outPatch->numYDivs == inPatch->numYDivs);
717 assert(outPatch->paddingLeft == inPatch->paddingLeft);
718 assert(outPatch->paddingRight == inPatch->paddingRight);
719 assert(outPatch->paddingTop == inPatch->paddingTop);
720 assert(outPatch->paddingBottom == inPatch->paddingBottom);
721 for (int i = 0; i < outPatch->numXDivs; i++) {
722 assert(outPatch->xDivs[i] == inPatch->xDivs[i]);
723 }
724 for (int i = 0; i < outPatch->numYDivs; i++) {
725 assert(outPatch->yDivs[i] == inPatch->yDivs[i]);
726 }
727 for (int i = 0; i < outPatch->numColors; i++) {
728 assert(outPatch->colors[i] == inPatch->colors[i]);
729 }
730 free(newData);
731}
732
733static bool patch_equals(Res_png_9patch& patch1, Res_png_9patch& patch2) {
734 if (!(patch1.numXDivs == patch2.numXDivs &&
735 patch1.numYDivs == patch2.numYDivs &&
736 patch1.numColors == patch2.numColors &&
737 patch1.paddingLeft == patch2.paddingLeft &&
738 patch1.paddingRight == patch2.paddingRight &&
739 patch1.paddingTop == patch2.paddingTop &&
740 patch1.paddingBottom == patch2.paddingBottom)) {
741 return false;
742 }
743 for (int i = 0; i < patch1.numColors; i++) {
744 if (patch1.colors[i] != patch2.colors[i]) {
745 return false;
746 }
747 }
748 for (int i = 0; i < patch1.numXDivs; i++) {
749 if (patch1.xDivs[i] != patch2.xDivs[i]) {
750 return false;
751 }
752 }
753 for (int i = 0; i < patch1.numYDivs; i++) {
754 if (patch1.yDivs[i] != patch2.yDivs[i]) {
755 return false;
756 }
757 }
758 return true;
759}
760
761static void dump_image(int w, int h, png_bytepp rows, int color_type)
762{
763 int i, j, rr, gg, bb, aa;
764
765 int bpp;
766 if (color_type == PNG_COLOR_TYPE_PALETTE || color_type == PNG_COLOR_TYPE_GRAY) {
767 bpp = 1;
768 } else if (color_type == PNG_COLOR_TYPE_GRAY_ALPHA) {
769 bpp = 2;
770 } else if (color_type == PNG_COLOR_TYPE_RGB || color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
771 // We use a padding byte even when there is no alpha
772 bpp = 4;
773 } else {
774 printf("Unknown color type %d.\n", color_type);
775 }
776
777 for (j = 0; j < h; j++) {
778 png_bytep row = rows[j];
779 for (i = 0; i < w; i++) {
780 rr = row[0];
781 gg = row[1];
782 bb = row[2];
783 aa = row[3];
784 row += bpp;
785
786 if (i == 0) {
787 printf("Row %d:", j);
788 }
789 switch (bpp) {
790 case 1:
791 printf(" (%d)", rr);
792 break;
793 case 2:
794 printf(" (%d %d", rr, gg);
795 break;
796 case 3:
797 printf(" (%d %d %d)", rr, gg, bb);
798 break;
799 case 4:
800 printf(" (%d %d %d %d)", rr, gg, bb, aa);
801 break;
802 }
803 if (i == (w - 1)) {
804 NOISY(printf("\n"));
805 }
806 }
807 }
808}
809
810#define MAX(a,b) ((a)>(b)?(a):(b))
811#define ABS(a) ((a)<0?-(a):(a))
812
813static void analyze_image(const char *imageName, image_info &imageInfo, int grayscaleTolerance,
814 png_colorp rgbPalette, png_bytep alphaPalette,
815 int *paletteEntries, bool *hasTransparency, int *colorType,
816 png_bytepp outRows)
817{
818 int w = imageInfo.width;
819 int h = imageInfo.height;
820 int i, j, rr, gg, bb, aa, idx;
821 uint32_t colors[256], col;
822 int num_colors = 0;
823 int maxGrayDeviation = 0;
824
825 bool isOpaque = true;
826 bool isPalette = true;
827 bool isGrayscale = true;
828
829 // Scan the entire image and determine if:
830 // 1. Every pixel has R == G == B (grayscale)
831 // 2. Every pixel has A == 255 (opaque)
832 // 3. There are no more than 256 distinct RGBA colors
833
834 // NOISY(printf("Initial image data:\n"));
835 // dump_image(w, h, imageInfo.rows, PNG_COLOR_TYPE_RGB_ALPHA);
836
837 for (j = 0; j < h; j++) {
838 png_bytep row = imageInfo.rows[j];
839 png_bytep out = outRows[j];
840 for (i = 0; i < w; i++) {
841 rr = *row++;
842 gg = *row++;
843 bb = *row++;
844 aa = *row++;
845
846 int odev = maxGrayDeviation;
847 maxGrayDeviation = MAX(ABS(rr - gg), maxGrayDeviation);
848 maxGrayDeviation = MAX(ABS(gg - bb), maxGrayDeviation);
849 maxGrayDeviation = MAX(ABS(bb - rr), maxGrayDeviation);
850 if (maxGrayDeviation > odev) {
851 NOISY(printf("New max dev. = %d at pixel (%d, %d) = (%d %d %d %d)\n",
852 maxGrayDeviation, i, j, rr, gg, bb, aa));
853 }
854
855 // Check if image is really grayscale
856 if (isGrayscale) {
857 if (rr != gg || rr != bb) {
858 NOISY(printf("Found a non-gray pixel at %d, %d = (%d %d %d %d)\n",
859 i, j, rr, gg, bb, aa));
860 isGrayscale = false;
861 }
862 }
863
864 // Check if image is really opaque
865 if (isOpaque) {
866 if (aa != 0xff) {
867 NOISY(printf("Found a non-opaque pixel at %d, %d = (%d %d %d %d)\n",
868 i, j, rr, gg, bb, aa));
869 isOpaque = false;
870 }
871 }
872
873 // Check if image is really <= 256 colors
874 if (isPalette) {
875 col = (uint32_t) ((rr << 24) | (gg << 16) | (bb << 8) | aa);
876 bool match = false;
877 for (idx = 0; idx < num_colors; idx++) {
878 if (colors[idx] == col) {
879 match = true;
880 break;
881 }
882 }
883
884 // Write the palette index for the pixel to outRows optimistically
885 // We might overwrite it later if we decide to encode as gray or
886 // gray + alpha
887 *out++ = idx;
888 if (!match) {
889 if (num_colors == 256) {
890 NOISY(printf("Found 257th color at %d, %d\n", i, j));
891 isPalette = false;
892 } else {
893 colors[num_colors++] = col;
894 }
895 }
896 }
897 }
898 }
899
900 *paletteEntries = 0;
901 *hasTransparency = !isOpaque;
902 int bpp = isOpaque ? 3 : 4;
903 int paletteSize = w * h + bpp * num_colors;
904
905 NOISY(printf("isGrayscale = %s\n", isGrayscale ? "true" : "false"));
906 NOISY(printf("isOpaque = %s\n", isOpaque ? "true" : "false"));
907 NOISY(printf("isPalette = %s\n", isPalette ? "true" : "false"));
908 NOISY(printf("Size w/ palette = %d, gray+alpha = %d, rgb(a) = %d\n",
909 paletteSize, 2 * w * h, bpp * w * h));
910 NOISY(printf("Max gray deviation = %d, tolerance = %d\n", maxGrayDeviation, grayscaleTolerance));
911
912 // Choose the best color type for the image.
913 // 1. Opaque gray - use COLOR_TYPE_GRAY at 1 byte/pixel
914 // 2. Gray + alpha - use COLOR_TYPE_PALETTE if the number of distinct combinations
915 // is sufficiently small, otherwise use COLOR_TYPE_GRAY_ALPHA
916 // 3. RGB(A) - use COLOR_TYPE_PALETTE if the number of distinct colors is sufficiently
917 // small, otherwise use COLOR_TYPE_RGB{_ALPHA}
918 if (isGrayscale) {
919 if (isOpaque) {
920 *colorType = PNG_COLOR_TYPE_GRAY; // 1 byte/pixel
921 } else {
922 // Use a simple heuristic to determine whether using a palette will
923 // save space versus using gray + alpha for each pixel.
924 // This doesn't take into account chunk overhead, filtering, LZ
925 // compression, etc.
926 if (isPalette && (paletteSize < 2 * w * h)) {
927 *colorType = PNG_COLOR_TYPE_PALETTE; // 1 byte/pixel + 4 bytes/color
928 } else {
929 *colorType = PNG_COLOR_TYPE_GRAY_ALPHA; // 2 bytes per pixel
930 }
931 }
932 } else if (isPalette && (paletteSize < bpp * w * h)) {
933 *colorType = PNG_COLOR_TYPE_PALETTE;
934 } else {
935 if (maxGrayDeviation <= grayscaleTolerance) {
936 printf("%s: forcing image to gray (max deviation = %d)\n", imageName, maxGrayDeviation);
937 *colorType = isOpaque ? PNG_COLOR_TYPE_GRAY : PNG_COLOR_TYPE_GRAY_ALPHA;
938 } else {
939 *colorType = isOpaque ? PNG_COLOR_TYPE_RGB : PNG_COLOR_TYPE_RGB_ALPHA;
940 }
941 }
942
943 // Perform postprocessing of the image or palette data based on the final
944 // color type chosen
945
946 if (*colorType == PNG_COLOR_TYPE_PALETTE) {
947 // Create separate RGB and Alpha palettes and set the number of colors
948 *paletteEntries = num_colors;
949
950 // Create the RGB and alpha palettes
951 for (int idx = 0; idx < num_colors; idx++) {
952 col = colors[idx];
953 rgbPalette[idx].red = (png_byte) ((col >> 24) & 0xff);
954 rgbPalette[idx].green = (png_byte) ((col >> 16) & 0xff);
955 rgbPalette[idx].blue = (png_byte) ((col >> 8) & 0xff);
956 alphaPalette[idx] = (png_byte) (col & 0xff);
957 }
958 } else if (*colorType == PNG_COLOR_TYPE_GRAY || *colorType == PNG_COLOR_TYPE_GRAY_ALPHA) {
959 // If the image is gray or gray + alpha, compact the pixels into outRows
960 for (j = 0; j < h; j++) {
961 png_bytep row = imageInfo.rows[j];
962 png_bytep out = outRows[j];
963 for (i = 0; i < w; i++) {
964 rr = *row++;
965 gg = *row++;
966 bb = *row++;
967 aa = *row++;
968
969 if (isGrayscale) {
970 *out++ = rr;
971 } else {
972 *out++ = (png_byte) (rr * 0.2126f + gg * 0.7152f + bb * 0.0722f);
973 }
974 if (!isOpaque) {
975 *out++ = aa;
976 }
977 }
978 }
979 }
980}
981
982
983static void write_png(const char* imageName,
984 png_structp write_ptr, png_infop write_info,
985 image_info& imageInfo, int grayscaleTolerance)
986{
987 bool optimize = true;
988 png_uint_32 width, height;
989 int color_type;
990 int bit_depth, interlace_type, compression_type;
991 int i;
992
993 png_unknown_chunk unknowns[2];
994 unknowns[0].data = NULL;
995 unknowns[1].data = NULL;
996
997 png_bytepp outRows = (png_bytepp) malloc((int) imageInfo.height * sizeof(png_bytep));
998 if (outRows == (png_bytepp) 0) {
999 printf("Can't allocate output buffer!\n");
1000 exit(1);
1001 }
1002 for (i = 0; i < (int) imageInfo.height; i++) {
1003 outRows[i] = (png_bytep) malloc(2 * (int) imageInfo.width);
1004 if (outRows[i] == (png_bytep) 0) {
1005 printf("Can't allocate output buffer!\n");
1006 exit(1);
1007 }
1008 }
1009
1010 png_set_compression_level(write_ptr, Z_BEST_COMPRESSION);
1011
1012 NOISY(printf("Writing image %s: w = %d, h = %d\n", imageName,
1013 (int) imageInfo.width, (int) imageInfo.height));
1014
1015 png_color rgbPalette[256];
1016 png_byte alphaPalette[256];
1017 bool hasTransparency;
1018 int paletteEntries;
1019
1020 analyze_image(imageName, imageInfo, grayscaleTolerance, rgbPalette, alphaPalette,
1021 &paletteEntries, &hasTransparency, &color_type, outRows);
1022
1023 // If the image is a 9-patch, we need to preserve it as a ARGB file to make
1024 // sure the pixels will not be pre-dithered/clamped until we decide they are
1025 if (imageInfo.is9Patch && (color_type == PNG_COLOR_TYPE_RGB ||
1026 color_type == PNG_COLOR_TYPE_GRAY || color_type == PNG_COLOR_TYPE_PALETTE)) {
1027 color_type = PNG_COLOR_TYPE_RGB_ALPHA;
1028 }
1029
1030 switch (color_type) {
1031 case PNG_COLOR_TYPE_PALETTE:
1032 NOISY(printf("Image %s has %d colors%s, using PNG_COLOR_TYPE_PALETTE\n",
1033 imageName, paletteEntries,
1034 hasTransparency ? " (with alpha)" : ""));
1035 break;
1036 case PNG_COLOR_TYPE_GRAY:
1037 NOISY(printf("Image %s is opaque gray, using PNG_COLOR_TYPE_GRAY\n", imageName));
1038 break;
1039 case PNG_COLOR_TYPE_GRAY_ALPHA:
1040 NOISY(printf("Image %s is gray + alpha, using PNG_COLOR_TYPE_GRAY_ALPHA\n", imageName));
1041 break;
1042 case PNG_COLOR_TYPE_RGB:
1043 NOISY(printf("Image %s is opaque RGB, using PNG_COLOR_TYPE_RGB\n", imageName));
1044 break;
1045 case PNG_COLOR_TYPE_RGB_ALPHA:
1046 NOISY(printf("Image %s is RGB + alpha, using PNG_COLOR_TYPE_RGB_ALPHA\n", imageName));
1047 break;
1048 }
1049
1050 png_set_IHDR(write_ptr, write_info, imageInfo.width, imageInfo.height,
1051 8, color_type, PNG_INTERLACE_NONE,
1052 PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
1053
1054 if (color_type == PNG_COLOR_TYPE_PALETTE) {
1055 png_set_PLTE(write_ptr, write_info, rgbPalette, paletteEntries);
1056 if (hasTransparency) {
1057 png_set_tRNS(write_ptr, write_info, alphaPalette, paletteEntries, (png_color_16p) 0);
1058 }
1059 png_set_filter(write_ptr, 0, PNG_NO_FILTERS);
1060 } else {
1061 png_set_filter(write_ptr, 0, PNG_ALL_FILTERS);
1062 }
1063
1064 if (imageInfo.is9Patch) {
1065 int chunk_count = 1 + (imageInfo.haveLayoutBounds ? 1 : 0);
1066 int p_index = imageInfo.haveLayoutBounds ? 1 : 0;
1067 int b_index = 0;
1068 png_byte *chunk_names = imageInfo.haveLayoutBounds
1069 ? (png_byte*)"npLb\0npTc\0"
1070 : (png_byte*)"npTc";
1071 NOISY(printf("Adding 9-patch info...\n"));
1072 strcpy((char*)unknowns[p_index].name, "npTc");
1073 unknowns[p_index].data = (png_byte*)imageInfo.info9Patch.serialize();
1074 unknowns[p_index].size = imageInfo.info9Patch.serializedSize();
1075 // TODO: remove the check below when everything works
1076 checkNinePatchSerialization(&imageInfo.info9Patch, unknowns[p_index].data);
1077
1078 if (imageInfo.haveLayoutBounds) {
1079 int chunk_size = sizeof(png_uint_32) * 4;
1080 strcpy((char*)unknowns[b_index].name, "npLb");
1081 unknowns[b_index].data = (png_byte*) calloc(chunk_size, 1);
1082 memcpy(unknowns[b_index].data, &imageInfo.layoutBoundsLeft, chunk_size);
1083 unknowns[b_index].size = chunk_size;
1084 }
1085
1086 for (int i = 0; i < chunk_count; i++) {
1087 unknowns[i].location = PNG_HAVE_PLTE;
1088 }
1089 png_set_keep_unknown_chunks(write_ptr, PNG_HANDLE_CHUNK_ALWAYS,
1090 chunk_names, chunk_count);
1091 png_set_unknown_chunks(write_ptr, write_info, unknowns, chunk_count);
1092#if PNG_LIBPNG_VER < 10600
1093 /* Deal with unknown chunk location bug in 1.5.x and earlier */
1094 png_set_unknown_chunk_location(write_ptr, write_info, 0, PNG_HAVE_PLTE);
1095 if (imageInfo.haveLayoutBounds) {
1096 png_set_unknown_chunk_location(write_ptr, write_info, 1, PNG_HAVE_PLTE);
1097 }
1098#endif
1099 }
1100
1101
1102 png_write_info(write_ptr, write_info);
1103
1104 png_bytepp rows;
1105 if (color_type == PNG_COLOR_TYPE_RGB || color_type == PNG_COLOR_TYPE_RGB_ALPHA) {
1106 if (color_type == PNG_COLOR_TYPE_RGB) {
1107 png_set_filler(write_ptr, 0, PNG_FILLER_AFTER);
1108 }
1109 rows = imageInfo.rows;
1110 } else {
1111 rows = outRows;
1112 }
1113 png_write_image(write_ptr, rows);
1114
1115// NOISY(printf("Final image data:\n"));
1116// dump_image(imageInfo.width, imageInfo.height, rows, color_type);
1117
1118 png_write_end(write_ptr, write_info);
1119
1120 for (i = 0; i < (int) imageInfo.height; i++) {
1121 free(outRows[i]);
1122 }
1123 free(outRows);
1124 free(unknowns[0].data);
1125 free(unknowns[1].data);
1126
1127 png_get_IHDR(write_ptr, write_info, &width, &height,
1128 &bit_depth, &color_type, &interlace_type,
1129 &compression_type, NULL);
1130
1131 NOISY(printf("Image written: w=%d, h=%d, d=%d, colors=%d, inter=%d, comp=%d\n",
1132 (int)width, (int)height, bit_depth, color_type, interlace_type,
1133 compression_type));
1134}
1135
1136status_t preProcessImage(const Bundle* bundle, const sp<AaptAssets>& assets,
1137 const sp<AaptFile>& file, String8* outNewLeafName)
1138{
1139 String8 ext(file->getPath().getPathExtension());
1140
1141 // We currently only process PNG images.
1142 if (strcmp(ext.string(), ".png") != 0) {
1143 return NO_ERROR;
1144 }
1145
1146 // Example of renaming a file:
1147 //*outNewLeafName = file->getPath().getBasePath().getFileName();
1148 //outNewLeafName->append(".nupng");
1149
1150 String8 printableName(file->getPrintableSource());
1151
1152 if (bundle->getVerbose()) {
1153 printf("Processing image: %s\n", printableName.string());
1154 }
1155
1156 png_structp read_ptr = NULL;
1157 png_infop read_info = NULL;
1158 FILE* fp;
1159
1160 image_info imageInfo;
1161
1162 png_structp write_ptr = NULL;
1163 png_infop write_info = NULL;
1164
1165 status_t error = UNKNOWN_ERROR;
1166
1167 const size_t nameLen = file->getPath().length();
1168
1169 fp = fopen(file->getSourceFile().string(), "rb");
1170 if (fp == NULL) {
1171 fprintf(stderr, "%s: ERROR: Unable to open PNG file\n", printableName.string());
1172 goto bail;
1173 }
1174
1175 read_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, 0, (png_error_ptr)NULL,
1176 (png_error_ptr)NULL);
1177 if (!read_ptr) {
1178 goto bail;
1179 }
1180
1181 read_info = png_create_info_struct(read_ptr);
1182 if (!read_info) {
1183 goto bail;
1184 }
1185
1186 if (setjmp(png_jmpbuf(read_ptr))) {
1187 goto bail;
1188 }
1189
1190 png_init_io(read_ptr, fp);
1191
1192 read_png(printableName.string(), read_ptr, read_info, &imageInfo);
1193
1194 if (nameLen > 6) {
1195 const char* name = file->getPath().string();
1196 if (name[nameLen-5] == '9' && name[nameLen-6] == '.') {
1197 if (do_9patch(printableName.string(), &imageInfo) != NO_ERROR) {
1198 goto bail;
1199 }
1200 }
1201 }
1202
1203 write_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, 0, (png_error_ptr)NULL,
1204 (png_error_ptr)NULL);
1205 if (!write_ptr)
1206 {
1207 goto bail;
1208 }
1209
1210 write_info = png_create_info_struct(write_ptr);
1211 if (!write_info)
1212 {
1213 goto bail;
1214 }
1215
1216 png_set_write_fn(write_ptr, (void*)file.get(),
1217 png_write_aapt_file, png_flush_aapt_file);
1218
1219 if (setjmp(png_jmpbuf(write_ptr)))
1220 {
1221 goto bail;
1222 }
1223
1224 write_png(printableName.string(), write_ptr, write_info, imageInfo,
1225 bundle->getGrayscaleTolerance());
1226
1227 error = NO_ERROR;
1228
1229 if (bundle->getVerbose()) {
1230 fseek(fp, 0, SEEK_END);
1231 size_t oldSize = (size_t)ftell(fp);
1232 size_t newSize = file->getSize();
1233 float factor = ((float)newSize)/oldSize;
1234 int percent = (int)(factor*100);
1235 printf(" (processed image %s: %d%% size of source)\n", printableName.string(), percent);
1236 }
1237
1238bail:
1239 if (read_ptr) {
1240 png_destroy_read_struct(&read_ptr, &read_info, (png_infopp)NULL);
1241 }
1242 if (fp) {
1243 fclose(fp);
1244 }
1245 if (write_ptr) {
1246 png_destroy_write_struct(&write_ptr, &write_info);
1247 }
1248
1249 if (error != NO_ERROR) {
1250 fprintf(stderr, "ERROR: Failure processing PNG image %s\n",
1251 file->getPrintableSource().string());
1252 }
1253 return error;
1254}
1255
1256status_t preProcessImageToCache(const Bundle* bundle, const String8& source, const String8& dest)
1257{
1258 png_structp read_ptr = NULL;
1259 png_infop read_info = NULL;
1260
1261 FILE* fp;
1262
1263 image_info imageInfo;
1264
1265 png_structp write_ptr = NULL;
1266 png_infop write_info = NULL;
1267
1268 status_t error = UNKNOWN_ERROR;
1269
1270 if (bundle->getVerbose()) {
1271 printf("Processing image to cache: %s => %s\n", source.string(), dest.string());
1272 }
1273
1274 // Get a file handler to read from
1275 fp = fopen(source.string(),"rb");
1276 if (fp == NULL) {
1277 fprintf(stderr, "%s ERROR: Unable to open PNG file\n", source.string());
1278 return error;
1279 }
1280
1281 // Call libpng to get a struct to read image data into
1282 read_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
1283 if (!read_ptr) {
1284 fclose(fp);
1285 png_destroy_read_struct(&read_ptr, &read_info,NULL);
1286 return error;
1287 }
1288
1289 // Call libpng to get a struct to read image info into
1290 read_info = png_create_info_struct(read_ptr);
1291 if (!read_info) {
1292 fclose(fp);
1293 png_destroy_read_struct(&read_ptr, &read_info,NULL);
1294 return error;
1295 }
1296
1297 // Set a jump point for libpng to long jump back to on error
1298 if (setjmp(png_jmpbuf(read_ptr))) {
1299 fclose(fp);
1300 png_destroy_read_struct(&read_ptr, &read_info,NULL);
1301 return error;
1302 }
1303
1304 // Set up libpng to read from our file.
1305 png_init_io(read_ptr,fp);
1306
1307 // Actually read data from the file
1308 read_png(source.string(), read_ptr, read_info, &imageInfo);
1309
1310 // We're done reading so we can clean up
1311 // Find old file size before releasing handle
1312 fseek(fp, 0, SEEK_END);
1313 size_t oldSize = (size_t)ftell(fp);
1314 fclose(fp);
1315 png_destroy_read_struct(&read_ptr, &read_info,NULL);
1316
1317 // Check to see if we're dealing with a 9-patch
1318 // If we are, process appropriately
1319 if (source.getBasePath().getPathExtension() == ".9") {
1320 if (do_9patch(source.string(), &imageInfo) != NO_ERROR) {
1321 return error;
1322 }
1323 }
1324
1325 // Call libpng to create a structure to hold the processed image data
1326 // that can be written to disk
1327 write_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
1328 if (!write_ptr) {
1329 png_destroy_write_struct(&write_ptr, &write_info);
1330 return error;
1331 }
1332
1333 // Call libpng to create a structure to hold processed image info that can
1334 // be written to disk
1335 write_info = png_create_info_struct(write_ptr);
1336 if (!write_info) {
1337 png_destroy_write_struct(&write_ptr, &write_info);
1338 return error;
1339 }
1340
1341 // Open up our destination file for writing
1342 fp = fopen(dest.string(), "wb");
1343 if (!fp) {
1344 fprintf(stderr, "%s ERROR: Unable to open PNG file\n", dest.string());
1345 png_destroy_write_struct(&write_ptr, &write_info);
1346 return error;
1347 }
1348
1349 // Set up libpng to write to our file
1350 png_init_io(write_ptr, fp);
1351
1352 // Set up a jump for libpng to long jump back on on errors
1353 if (setjmp(png_jmpbuf(write_ptr))) {
1354 fclose(fp);
1355 png_destroy_write_struct(&write_ptr, &write_info);
1356 return error;
1357 }
1358
1359 // Actually write out to the new png
1360 write_png(dest.string(), write_ptr, write_info, imageInfo,
1361 bundle->getGrayscaleTolerance());
1362
1363 if (bundle->getVerbose()) {
1364 // Find the size of our new file
1365 FILE* reader = fopen(dest.string(), "rb");
1366 fseek(reader, 0, SEEK_END);
1367 size_t newSize = (size_t)ftell(reader);
1368 fclose(reader);
1369
1370 float factor = ((float)newSize)/oldSize;
1371 int percent = (int)(factor*100);
1372 printf(" (processed image to cache entry %s: %d%% size of source)\n",
1373 dest.string(), percent);
1374 }
1375
1376 //Clean up
1377 fclose(fp);
1378 png_destroy_write_struct(&write_ptr, &write_info);
1379
1380 return NO_ERROR;
1381}
1382
1383status_t postProcessImage(const sp<AaptAssets>& assets,
1384 ResourceTable* table, const sp<AaptFile>& file)
1385{
1386 String8 ext(file->getPath().getPathExtension());
1387
1388 // At this point, now that we have all the resource data, all we need to
1389 // do is compile XML files.
1390 if (strcmp(ext.string(), ".xml") == 0) {
1391 return compileXmlFile(assets, file, table);
1392 }
1393
1394 return NO_ERROR;
1395}