Skip to content

Commit a3b2ad5

Browse files
committed
Rewrite image alpha detection for better readability
1 parent c3f706d commit a3b2ad5

File tree

1 file changed

+30
-17
lines changed

1 file changed

+30
-17
lines changed

lib/imageio.c

Lines changed: 30 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -62,24 +62,37 @@ mapcache_image_alpha_type mapcache_imageio_alpha_sniff(mapcache_context *ctx, ma
6262
{
6363
const unsigned char * b = buffer->buf;
6464
mapcache_image_format_type t = mapcache_imageio_header_sniff(ctx,buffer);
65-
if (t==GC_JPEG) {
66-
// A JPG file is opaque
67-
return MC_ALPHA_NO;
68-
} else if (t==GC_PNG && buffer->size >= 26 && (b[12]|32) == 'i' && (b[13]|32) == 'h' && (b[14]|32) == 'd' && (b[15]|32) == 'r') {
69-
// Check color type of PNG file in IHDR chunk
70-
if (b[25] == 0 || b[25] == 2) {
71-
// Gray or RGB without alpha
72-
return MC_ALPHA_NO;
73-
} else if (b[25] == 4 || b[25] == 6) {
74-
// Gray or RGB with alpha
75-
return MC_ALPHA_YES;
76-
} else {
77-
// TODO: Should check palette index
78-
return MC_ALPHA_UNKNOWN;
79-
}
80-
} else {
81-
return MC_ALPHA_UNKNOWN;
65+
mapcache_image_alpha_type alpha_type;
66+
67+
switch (t) {
68+
case GC_JPEG:
69+
// JPEG files are opaque
70+
alpha_type = MC_ALPHA_NO;
71+
break;
72+
case GC_PNG:
73+
if (buffer->size >= 26) {
74+
// Check color type of PNG file in IHDR chunk
75+
if ( (b[12]|32)=='i' && (b[13]|32)=='h' && (b[14]|32)=='d' && (b[15]|32)=='r' ) {
76+
switch (b[25]) {
77+
case 4:
78+
case 6:
79+
// Gray or RGB with alpha
80+
alpha_type = MC_ALPHA_YES;
81+
break;
82+
default:
83+
// Other colortypes have no alpha channel
84+
alpha_type = MC_ALPHA_NO;
85+
}
86+
}
87+
} else {
88+
alpha_type = MC_ALPHA_UNKNOWN;
89+
}
90+
break;
91+
default:
92+
alpha_type = MC_ALPHA_UNKNOWN;
93+
break;
8294
}
95+
return alpha_type;
8396
}
8497

8598
mapcache_image* mapcache_imageio_decode(mapcache_context *ctx, mapcache_buffer *buffer)

0 commit comments

Comments
 (0)