alpha_blend.cc (1892B)
1 // Copyright (c) the JPEG XL Project Authors. All rights reserved. 2 // 3 // Use of this source code is governed by a BSD-style 4 // license that can be found in the LICENSE file. 5 6 #include "lib/extras/alpha_blend.h" 7 8 #include "lib/extras/packed_image.h" 9 10 namespace jxl { 11 namespace extras { 12 13 namespace { 14 15 void AlphaBlend(PackedFrame* frame, const float background[3]) { 16 if (!frame) return; 17 const PackedImage& im = frame->color; 18 JxlPixelFormat format = im.format; 19 if (format.num_channels != 2 && format.num_channels != 4) { 20 return; 21 } 22 --format.num_channels; 23 PackedImage blended(im.xsize, im.ysize, format); 24 // TODO(szabadka) SIMDify this and make it work for float16. 25 for (size_t y = 0; y < im.ysize; ++y) { 26 for (size_t x = 0; x < im.xsize; ++x) { 27 if (format.num_channels == 2) { 28 float g = im.GetPixelValue(y, x, 0); 29 float a = im.GetPixelValue(y, x, 1); 30 float out = g * a + background[0] * (1 - a); 31 blended.SetPixelValue(y, x, 0, out); 32 } else { 33 float r = im.GetPixelValue(y, x, 0); 34 float g = im.GetPixelValue(y, x, 1); 35 float b = im.GetPixelValue(y, x, 2); 36 float a = im.GetPixelValue(y, x, 3); 37 float out_r = r * a + background[0] * (1 - a); 38 float out_g = g * a + background[1] * (1 - a); 39 float out_b = b * a + background[2] * (1 - a); 40 blended.SetPixelValue(y, x, 0, out_r); 41 blended.SetPixelValue(y, x, 1, out_g); 42 blended.SetPixelValue(y, x, 2, out_b); 43 } 44 } 45 } 46 frame->color = blended.Copy(); 47 } 48 49 } // namespace 50 51 void AlphaBlend(PackedPixelFile* ppf, const float background[3]) { 52 if (!ppf || ppf->info.alpha_bits == 0) { 53 return; 54 } 55 ppf->info.alpha_bits = 0; 56 AlphaBlend(ppf->preview_frame.get(), background); 57 for (auto& frame : ppf->frames) { 58 AlphaBlend(&frame, background); 59 } 60 } 61 62 } // namespace extras 63 } // namespace jxl