cid#1640468 Dereference after null check
[LibreOffice.git] / vcl / source / bitmap / BitmapPopArtFilter.cxx
blob375539f3168da882299b3ce1fbd4699be8fd27e1
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 /*
3 * This file is part of the LibreOffice project.
5 * This Source Code Form is subject to the terms of the Mozilla Public
6 * License, v. 2.0. If a copy of the MPL was not distributed with this
7 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
9 */
11 #include <tools/solar.h>
13 #include <vcl/bitmap/BitmapPopArtFilter.hxx>
14 #include <vcl/BitmapWriteAccess.hxx>
16 BitmapEx BitmapPopArtFilter::execute(BitmapEx const& rBitmapEx) const
18 Bitmap aBitmap(rBitmapEx.GetBitmap());
20 bool bConvert = isPalettePixelFormat(aBitmap.getPixelFormat())
21 || aBitmap.Convert(BmpConversion::N8BitColors);
23 if (!bConvert)
24 return BitmapEx();
26 BitmapScopedWriteAccess pWriteAcc(aBitmap);
28 if (!pWriteAcc)
29 return BitmapEx();
31 const sal_Int32 nWidth = pWriteAcc->Width();
32 const sal_Int32 nHeight = pWriteAcc->Height();
33 const sal_uInt16 nEntryCount = 1 << pWriteAcc->GetBitCount();
34 sal_uInt16 n = 0;
35 std::vector<PopArtEntry> aPopArtTable(nEntryCount);
37 for (n = 0; n < nEntryCount; n++)
39 PopArtEntry& rEntry = aPopArtTable[n];
40 rEntry.mnIndex = n;
41 rEntry.mnCount = 0;
44 // get pixel count for each palette entry
45 for (sal_Int32 nY = 0; nY < nHeight; nY++)
47 Scanline pScanline = pWriteAcc->GetScanline(nY);
48 for (sal_Int32 nX = 0; nX < nWidth; nX++)
50 aPopArtTable[pWriteAcc->GetIndexFromData(pScanline, nX)].mnCount++;
51 assert(aPopArtTable[pWriteAcc->GetIndexFromData(pScanline, nX)].mnCount != 0);
55 // sort table
56 std::sort(
57 aPopArtTable.begin(), aPopArtTable.end(),
58 [](const PopArtEntry& lhs, const PopArtEntry& rhs) { return lhs.mnCount > rhs.mnCount; });
60 // get last used entry
61 sal_uInt16 nFirstEntry;
62 sal_uInt16 nLastEntry = 0;
64 for (n = 0; n < nEntryCount; n++)
66 if (aPopArtTable[n].mnCount)
67 nLastEntry = n;
70 // rotate palette (one entry)
71 const BitmapColor aFirstCol(pWriteAcc->GetPaletteColor(aPopArtTable[0].mnIndex));
73 for (nFirstEntry = 0; nFirstEntry < nLastEntry; nFirstEntry++)
75 pWriteAcc->SetPaletteColor(
76 aPopArtTable[nFirstEntry].mnIndex,
77 pWriteAcc->GetPaletteColor(aPopArtTable[nFirstEntry + 1].mnIndex));
80 pWriteAcc->SetPaletteColor(aPopArtTable[nLastEntry].mnIndex, aFirstCol);
82 // cleanup
83 pWriteAcc.reset();
85 return BitmapEx(aBitmap);
88 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */