KiCad PCB EDA Suite
Loading...
Searching...
No Matches
bitmap_base.cpp
Go to the documentation of this file.
1/*
2 * This program source code file is part of KiCad, a free EDA CAD application.
3 *
4 * Copyright (C) 2017 jean-pierre.charras
5 * Copyright The KiCad Developers, see AUTHORS.txt for contributors.
6 *
7 * This program is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation; either version 2
10 * of the License, or (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, you may find one here:
19 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
20 * or you may search the http://www.gnu.org website for the version 2 license,
21 * or you may write to the Free Software Foundation, Inc.,
22 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
23 */
24
25#include "bitmap_base.h"
26
27#include <algorithm> // for std::swap
28#include <cstring> // for memcpy
29#include <gr_basic.h>
30#include <math/util.h> // for KiROUND
31#include <memory> // for make_unique, unique_ptr
32#include <plotters/plotter.h>
33#include <richio.h>
34#include <wx/bitmap.h> // for wxBitmap
35#include <wx/mstream.h>
36#include <wx/stream.h> // for wxInputStream, wxOutputStream
37#include <wx/string.h> // for wxString
38#include <wx/wfstream.h> // for wxFileInputStream
39
40
41
43{
44 m_scale = 1.0; // 1.0 = original bitmap size
45 m_imageType = wxBITMAP_TYPE_INVALID;
46 m_bitmap = nullptr;
47 m_bitmapDirty = false;
48 m_image = nullptr;
49 m_originalImage = nullptr;
50 m_ppi = 300; // the bitmap definition. the default is 300PPI
51 m_pixelSizeIu = 254000.0 / m_ppi; // a pixel size value OK for bitmaps using 300 PPI
52 // for Eeschema which uses currently 254000PPI
53 m_isMirroredX = false;
54 m_isMirroredY = false;
56}
57
58
60{
61 m_scale = aSchBitmap.m_scale;
62 m_ppi = aSchBitmap.m_ppi;
63 m_pixelSizeIu = aSchBitmap.m_pixelSizeIu;
64 m_isMirroredX = aSchBitmap.m_isMirroredX;
65 m_isMirroredY = aSchBitmap.m_isMirroredY;
66 m_rotation = aSchBitmap.m_rotation;
67 m_imageType = aSchBitmap.m_imageType;
68
69 m_image = nullptr;
70 m_bitmap = nullptr;
71 m_bitmapDirty = false;
72 m_originalImage = nullptr;
73
74 if( aSchBitmap.m_image )
75 {
76 m_image = new wxImage( *aSchBitmap.m_image );
77 m_bitmap = new wxBitmap( *m_image );
78 m_originalImage = new wxImage( *aSchBitmap.m_originalImage );
79 m_imageType = aSchBitmap.m_imageType;
80 m_imageData = aSchBitmap.m_imageData;
81 m_imageId = aSchBitmap.m_imageId;
82 }
83}
84
85
86void BITMAP_BASE::rebuildBitmap( bool aResetID )
87{
88 if( m_bitmap )
89 delete m_bitmap;
90
91 m_bitmap = new wxBitmap( *m_image );
92 m_bitmapDirty = false;
93
94 if( aResetID )
95 m_imageId = KIID();
96
97}
98
99
101{
102 if( m_bitmapDirty && m_image )
103 {
104 if( m_bitmap )
105 delete m_bitmap;
106
107 m_bitmap = new wxBitmap( *m_image );
108 m_bitmapDirty = false;
109 }
110}
111
112
114{
115 // Todo: eventually we need to support dpi / scaling in both dimensions
116 //
117 // PNG stores resolution as pixels-per-meter in the pHYs chunk. wxWidgets converts this
118 // to pixels-per-cm as a floating-point string (e.g., 3780 PPM -> "37.8" px/cm).
119 // GetOptionInt() would truncate "37.8" to 37 before the * 2.54 multiply, causing ~2%
120 // error for common resolutions. ToCDouble is locale-independent unlike wxAtof.
121 wxString resStr = m_originalImage->GetOption( wxIMAGE_OPTION_RESOLUTIONX );
122 double dpiX = 0.0;
123 resStr.ToCDouble( &dpiX );
124
125 if( dpiX > 1.0 )
126 {
127 if( m_originalImage->GetOptionInt( wxIMAGE_OPTION_RESOLUTIONUNIT ) == wxIMAGE_RESOLUTION_CM )
128 m_ppi = KiROUND( dpiX * 2.54 );
129 else
130 m_ppi = KiROUND( dpiX );
131 }
132}
133
134
136{
137 *m_image = *aItem.m_image;
139 m_imageId = aItem.m_imageId;
140 m_scale = aItem.m_scale;
141 m_ppi = aItem.m_ppi;
145 m_rotation = aItem.m_rotation;
146 m_imageType = aItem.m_imageType;
147 m_imageData = aItem.m_imageData;
148
149 rebuildBitmap( false );
150}
151
152
153bool BITMAP_BASE::ReadImageFile( wxInputStream& aInStream )
154{
155 // Store the original image data in m_imageData
156 size_t dataSize = aInStream.GetLength();
157 m_imageData.SetBufSize( dataSize );
158 aInStream.Read( m_imageData.GetData(), dataSize );
159 m_imageData.SetDataLen( dataSize );
160
161 std::unique_ptr<wxImage> new_image = std::make_unique<wxImage>();
162
163 // Load the image from the stream into new_image
164 wxMemoryInputStream mem_stream( m_imageData.GetData(), dataSize );
165 if( !new_image->LoadFile( mem_stream ) )
166 return false;
167
168 return SetImage( *new_image );
169}
170
171
172bool BITMAP_BASE::ReadImageFile( wxMemoryBuffer& aBuf )
173{
174 // Store the original image data in m_imageData
175 m_imageData = aBuf;
176
177 std::unique_ptr<wxImage> new_image = std::make_unique<wxImage>();
178
179 // Load the image from the buffer into new_image
180 wxMemoryInputStream mem_stream( m_imageData.GetData(), m_imageData.GetBufSize() );
181
182 if( !new_image->LoadFile( mem_stream ) )
183 return false;
184
185 return SetImage( *new_image );
186}
187
188
189bool BITMAP_BASE::ReadImageFile(const wxString& aFullFilename)
190{
191 wxFileInputStream file_stream(aFullFilename);
192
193 // Check if the file could be opened successfully
194 if (!file_stream.IsOk())
195 return false;
196
197 return ReadImageFile(file_stream);
198}
199
200
201bool BITMAP_BASE::SetImage( const wxImage& aImage )
202{
203 if( !aImage.IsOk() || aImage.GetWidth() == 0 || aImage.GetHeight() == 0 )
204 return false;
205
206 delete m_image;
207 m_image = new wxImage( aImage );
208
209 // Create a new wxImage object from m_image
210 delete m_originalImage;
211 m_originalImage = new wxImage( *m_image );
212
214 updatePPI();
215
216 return true;
217}
218
219
220bool BITMAP_BASE::SaveImageData( wxOutputStream& aOutStream ) const
221{
222 if( m_imageData.IsEmpty() )
223 {
224 // If m_imageData is empty, use wxImage::Save() method to write m_image contents to
225 // the stream.
226 wxBitmapType type = m_imageType == wxBITMAP_TYPE_JPEG ? wxBITMAP_TYPE_JPEG
227 : wxBITMAP_TYPE_PNG;
228
229 if( !m_image->SaveFile( aOutStream, type ) )
230 {
231 return false;
232 }
233 }
234 else
235 {
236 // Write the contents of m_imageData to the stream.
237 aOutStream.Write( m_imageData.GetData(), m_imageData.GetDataLen() );
238 }
239
240 return true;
241}
242
243
244bool BITMAP_BASE::LoadLegacyData( LINE_READER& aLine, wxString& aErrorMsg )
245{
246 wxMemoryOutputStream stream;
247 char* line;
248
249 while( true )
250 {
251 if( !aLine.ReadLine() )
252 {
253 aErrorMsg = wxT( "Unexpected end of data" );
254 return false;
255 }
256
257 line = aLine.Line();
258
259 if( strncasecmp( line, "EndData", 4 ) == 0 )
260 {
261 // all the PNG date is read.
262 // We expect here m_image and m_bitmap are void
263 m_image = new wxImage();
264 wxMemoryInputStream istream( stream );
265 m_image->LoadFile( istream, wxBITMAP_TYPE_ANY );
266 m_bitmap = new wxBitmap( *m_image );
267 m_originalImage = new wxImage( *m_image );
269 break;
270 }
271
272 // Read PNG data, stored in hexadecimal,
273 // each byte = 2 hexadecimal digits and a space between 2 bytes
274 // and put it in memory stream buffer
275 int len = strlen( line );
276
277 for( ; len > 0; len -= 3, line += 3 )
278 {
279 int value = 0;
280
281 if( sscanf( line, "%X", &value ) == 1 )
282 stream.PutC( (char) value );
283 else
284 break;
285 }
286 }
287
288 return true;
289}
290
291
293{
294 BOX2I bbox;
295 VECTOR2I size = GetSize();
296
297 bbox.Inflate( size.x / 2, size.y / 2 );
298
299 return bbox;
300}
301
302
303void BITMAP_BASE::DrawBitmap( wxDC* aDC, const VECTOR2I& aPos,
304 const KIGFX::COLOR4D& aBackgroundColor ) const
305{
307
308 if( m_bitmap == nullptr )
309 return;
310
311 VECTOR2I pos = aPos;
312 VECTOR2I size = GetSize();
313
314 // This fixes a bug in OSX that should be fixed in the 3.0.3 version or later.
315 if( ( size.x == 0 ) || ( size.y == 0 ) )
316 return;
317
318 // To draw the bitmap, pos is the upper left corner position
319 pos.x -= size.x / 2;
320 pos.y -= size.y / 2;
321
322 double scale;
323 int logicalOriginX, logicalOriginY;
324 aDC->GetUserScale( &scale, &scale );
325 aDC->GetLogicalOrigin( &logicalOriginX, &logicalOriginY );
326
327 // We already have issues to draw a bitmap on the wxDC, depending on wxWidgets version.
328 // Now we have an issue on wxWidgets 3.1.6 to fix the clip area
329 // and the bitmap position when using TransformMatrix
330 // So for version == 3.1.6 do not use it
331 // Be careful before changing the code.
332 bool useTransform = aDC->CanUseTransformMatrix();
333
334 wxAffineMatrix2D init_matrix = aDC->GetTransformMatrix();
335
336 // Note: clipping bitmap area was made to fix a minor issue in old versions of
337 // KiCad/wxWidgets (5.1 / wx 3.0)
338 // However SetClippingRegion creates a lot of issues (different ways to fix the
339 // position and size of the area, depending on wxWidgets version)because it changes with
340 // each versions of wxWidgets, so it is now disabled
341 // However the code is still here, just in case
342 // #define USE_CLIP_AREA
343
344 wxPoint clipAreaPos;
345
346 if( useTransform )
347 {
348 wxAffineMatrix2D matrix = aDC->GetTransformMatrix();
349 matrix.Translate( pos.x, pos.y );
350 matrix.Scale( GetScalingFactor(), GetScalingFactor() );
351 aDC->SetTransformMatrix( matrix );
352
353 // Needed on wx <= 3.1.5, and this is strange...
354 // Nevertheless, this code has problem (the bitmap is not seen)
355 // with wx version > 3.1.5
356 clipAreaPos.x = pos.x;
357 clipAreaPos.y = pos.y;
358
359 pos.x = pos.y = 0;
360 }
361 else
362 {
363 aDC->SetUserScale( scale * GetScalingFactor(), scale * GetScalingFactor() );
364 aDC->SetLogicalOrigin( logicalOriginX / GetScalingFactor(),
365 logicalOriginY / GetScalingFactor() );
366
367 pos.x = KiROUND( pos.x / GetScalingFactor() );
368 pos.y = KiROUND( pos.y / GetScalingFactor() );
369 size.x = KiROUND( size.x / GetScalingFactor() );
370 size.y = KiROUND( size.y / GetScalingFactor() );
371 clipAreaPos.x = pos.x;
372 clipAreaPos.y = pos.y;
373 }
374
375#ifdef USE_CLIP_AREA
376 aDC->DestroyClippingRegion();
377 aDC->SetClippingRegion( clipAreaPos, wxSize( size.x, size.y ) );
378#endif
379
380 if( aBackgroundColor != COLOR4D::UNSPECIFIED && m_bitmap->HasAlpha() )
381 {
382 // Most printers don't support transparent images properly,
383 // so blend the image with background color.
384
385 int w = m_bitmap->GetWidth();
386 int h = m_bitmap->GetHeight();
387
388 wxImage image( w, h );
389 wxColour bgColor = aBackgroundColor.ToColour();
390
391 image.SetRGB( wxRect( 0, 0, w, h ), bgColor.Red(), bgColor.Green(), bgColor.Blue() );
392 image.Paste( m_bitmap->ConvertToImage(), 0, 0, wxIMAGE_ALPHA_BLEND_COMPOSE );
393
395 image = image.ConvertToGreyscale();
396
397 aDC->DrawBitmap( wxBitmap( image ), pos.x, pos.y, true );
398 }
399 else if( GetGRForceBlackPenState() )
400 {
401 wxBitmap result( m_bitmap->ConvertToImage().ConvertToGreyscale() );
402 aDC->DrawBitmap( result, pos.x, pos.y, true );
403 }
404 else
405 {
406 aDC->DrawBitmap( *m_bitmap, pos.x, pos.y, true );
407 }
408
409 if( useTransform )
410 aDC->SetTransformMatrix( init_matrix );
411 else
412 {
413 aDC->SetUserScale( scale, scale );
414 aDC->SetLogicalOrigin( logicalOriginX, logicalOriginY );
415 }
416
417#ifdef USE_CLIP_AREA
418 aDC->DestroyClippingRegion();
419#endif
420}
421
422
424{
425 VECTOR2I size;
426
427 if( m_image )
428 {
429 size.x = KiROUND( m_image->GetWidth() * GetScalingFactor() );
430 size.y = KiROUND( m_image->GetHeight() * GetScalingFactor() );
431 }
432
433 return size;
434}
435
436
437void BITMAP_BASE::mirrorImageInPlace( wxImage& aImage, FLIP_DIRECTION aFlipDirection )
438{
439 const int w = aImage.GetWidth();
440 const int h = aImage.GetHeight();
441
442 if( w == 0 || h == 0 )
443 return;
444
445 unsigned char* rgb = aImage.GetData();
446 unsigned char* alpha = aImage.HasAlpha() ? aImage.GetAlpha() : nullptr;
447 const int bpp = 3;
448
449 if( aFlipDirection == FLIP_DIRECTION::LEFT_RIGHT )
450 {
451 // Swap columns left-to-right within each row
452 for( int y = 0; y < h; ++y )
453 {
454 unsigned char* rowRgb = rgb + y * w * bpp;
455
456 for( int lo = 0, hi = w - 1; lo < hi; ++lo, --hi )
457 {
458 std::swap( rowRgb[lo * bpp + 0], rowRgb[hi * bpp + 0] );
459 std::swap( rowRgb[lo * bpp + 1], rowRgb[hi * bpp + 1] );
460 std::swap( rowRgb[lo * bpp + 2], rowRgb[hi * bpp + 2] );
461 }
462
463 if( alpha )
464 {
465 unsigned char* rowAlpha = alpha + y * w;
466
467 for( int lo = 0, hi = w - 1; lo < hi; ++lo, --hi )
468 std::swap( rowAlpha[lo], rowAlpha[hi] );
469 }
470 }
471 }
472 else
473 {
474 // Swap entire rows top-to-bottom
475 const size_t rowBytes = w * bpp;
476 std::vector<unsigned char> tmpRgb( rowBytes );
477
478 for( int lo = 0, hi = h - 1; lo < hi; ++lo, --hi )
479 {
480 unsigned char* rowLo = rgb + lo * rowBytes;
481 unsigned char* rowHi = rgb + hi * rowBytes;
482 memcpy( tmpRgb.data(), rowLo, rowBytes );
483 memcpy( rowLo, rowHi, rowBytes );
484 memcpy( rowHi, tmpRgb.data(), rowBytes );
485 }
486
487 if( alpha )
488 {
489 std::vector<unsigned char> tmpAlpha( w );
490
491 for( int lo = 0, hi = h - 1; lo < hi; ++lo, --hi )
492 {
493 unsigned char* aLo = alpha + lo * w;
494 unsigned char* aHi = alpha + hi * w;
495 memcpy( tmpAlpha.data(), aLo, w );
496 memcpy( aLo, aHi, w );
497 memcpy( aHi, tmpAlpha.data(), w );
498 }
499 }
500 }
501}
502
503
505{
506 if( m_image )
507 {
508 mirrorImageInPlace( *m_image, aFlipDirection );
509
510 if( aFlipDirection == FLIP_DIRECTION::TOP_BOTTOM )
512 else
514
515 m_bitmapDirty = true;
516 m_imageData.Clear();
517 }
518}
519
520
521void BITMAP_BASE::Rotate( bool aRotateCCW )
522{
523 if( m_image )
524 {
525 // wxImage::Rotate90() clears resolution metadata, so preserve it.
526 // Use string form to avoid truncating fractional pixels/cm values.
527 wxString resX = m_image->GetOption( wxIMAGE_OPTION_RESOLUTIONX );
528 wxString resY = m_image->GetOption( wxIMAGE_OPTION_RESOLUTIONY );
529 int unit = m_image->GetOptionInt( wxIMAGE_OPTION_RESOLUTIONUNIT );
530
531 // wxImage::Rotate90 parameter is "clockwise", so invert for CCW rotation
532 *m_image = m_image->Rotate90( !aRotateCCW );
533
534 m_image->SetOption( wxIMAGE_OPTION_RESOLUTIONUNIT, unit );
535 m_image->SetOption( wxIMAGE_OPTION_RESOLUTIONX, resX );
536 m_image->SetOption( wxIMAGE_OPTION_RESOLUTIONY, resY );
537
538 m_rotation += ( aRotateCCW ? ANGLE_90 : -ANGLE_90 );
539 m_bitmapDirty = true;
540 m_imageData.Clear();
541 }
542}
543
544
546{
547 if( m_image )
548 {
549 *m_image = m_image->ConvertToGreyscale();
550 *m_originalImage = m_originalImage->ConvertToGreyscale();
551 m_bitmapDirty = true;
552 m_imageData.Clear();
553 m_imageId = KIID();
554 }
555}
556
557
558void BITMAP_BASE::PlotImage( PLOTTER* aPlotter, const VECTOR2I& aPos,
559 const COLOR4D& aDefaultColor,
560 int aDefaultPensize ) const
561{
562 if( m_image == nullptr )
563 return;
564
565 // These 2 lines are useful only for plotters that cannot plot a bitmap
566 // and plot a rectangle instead of.
567 aPlotter->SetColor( aDefaultColor );
568 aPlotter->SetCurrentLineWidth( aDefaultPensize );
569 aPlotter->PlotImage( *m_image, aPos, GetScalingFactor() );
570}
571
572
574{
575 if( m_image )
576 {
577 wxMemoryOutputStream stream;
578 wxBitmapType type = m_imageType == wxBITMAP_TYPE_JPEG ? wxBITMAP_TYPE_JPEG
579 : wxBITMAP_TYPE_PNG;
580
581 if( !m_image->SaveFile( stream, type ) )
582 return;
583
584 m_imageData.GetWriteBuf( stream.GetLength() );
585 stream.CopyTo( m_imageData.GetData(), stream.GetLength() );
586 m_imageData.SetDataLen( stream.GetLength() );
587 }
588}
BOX2< VECTOR2I > BOX2I
Definition box2.h:922
constexpr BOX2I KiROUND(const BOX2D &aBoxD)
Definition box2.h:990
void ensureBitmapUpToDate() const
Ensure the cached wxBitmap is up-to-date with the current wxImage.
wxMemoryBuffer m_imageData
Cached encoded image data (PNG/JPEG).
void Rotate(bool aRotateCCW)
Rotate image CW or CCW.
bool LoadLegacyData(LINE_READER &aLine, wxString &aErrorMsg)
Load an image data saved by #SaveData.
void updateImageDataBuffer()
Resets the image data buffer using the current image data.
double GetScalingFactor() const
This scaling factor depends on m_pixelSizeIu and m_scale.
Definition bitmap_base.h:94
void PlotImage(PLOTTER *aPlotter, const VECTOR2I &aPos, const KIGFX::COLOR4D &aDefaultColor, int aDefaultPensize) const
Plot bitmap on plotter.
void Mirror(FLIP_DIRECTION aFlipDirection)
Mirror image vertically (i.e.
const BOX2I GetBoundingBox() const
Return the orthogonal, bounding box of this object for display purposes.
bool m_isMirroredY
bool m_isMirroredX
void ImportData(BITMAP_BASE &aItem)
Copy aItem image to this object and update m_bitmap.
bool m_bitmapDirty
True when m_bitmap needs rebuilding from m_image.
bool SaveImageData(wxOutputStream &aOutStream) const
Write the bitmap data to aOutStream.
wxImage * m_originalImage
Raw image data, not transformed by rotate/mirror.
void rebuildBitmap(bool aResetID=true)
Rebuild the internal bitmap used to draw/plot image.
static void mirrorImageInPlace(wxImage &aImage, FLIP_DIRECTION aFlipDirection)
Mirror the wxImage pixel data in-place without allocating a new image.
wxBitmapType m_imageType
The image type (png, jpeg, etc.).
wxBitmap * m_bitmap
The bitmap used to draw/plot image.
void ConvertToGreyscale()
bool SetImage(const wxImage &aImage)
Set the image from an existing wxImage.
bool ReadImageFile(const wxString &aFullFilename)
Reads and stores in memory an image file.
wxImage * m_image
The raw, uncompressed image data.
double m_scale
The scaling factor of the bitmap with m_pixelSizeIu, controls the actual draw size.
double m_pixelSizeIu
The scaling factor of the bitmap to convert the bitmap size (in pixels) to internal KiCad units.
int m_ppi
The bitmap definition. The default is 300PPI.
void DrawBitmap(wxDC *aDC, const VECTOR2I &aPos, const KIGFX::COLOR4D &aBackgroundColor=KIGFX::COLOR4D::UNSPECIFIED) const
BITMAP_BASE(const VECTOR2I &pos=VECTOR2I(0, 0))
VECTOR2I GetSize() const
EDA_ANGLE m_rotation
constexpr BOX2< Vec > & Inflate(coord_type dx, coord_type dy)
Inflates the rectangle horizontally by dx and vertically by dy.
Definition box2.h:558
static const COLOR4D UNSPECIFIED
For legacy support; used as a value to indicate color hasn't been set yet.
Definition color4d.h:402
A color representation with 4 components: red, green, blue, alpha.
Definition color4d.h:105
wxColour ToColour() const
Definition color4d.cpp:225
Definition kiid.h:48
An abstract class from which implementation specific LINE_READERs may be derived to read single lines...
Definition richio.h:66
virtual char * ReadLine()=0
Read a line of text into the buffer and increments the line number counter.
char * Line() const
Return a pointer to the last line that was read in.
Definition richio.h:102
Base plotter engine class.
Definition plotter.h:136
virtual void PlotImage(const wxImage &aImage, const VECTOR2I &aPos, double aScaleFactor)
Only PostScript plotters can plot bitmaps.
Definition plotter.cpp:260
virtual void SetCurrentLineWidth(int width, void *aData=nullptr)=0
Set the line width for the next drawing.
virtual void SetColor(const COLOR4D &color)=0
static constexpr EDA_ANGLE ANGLE_0
Definition eda_angle.h:411
static constexpr EDA_ANGLE ANGLE_90
Definition eda_angle.h:413
bool GetGRForceBlackPenState(void)
Definition gr_basic.cpp:165
FLIP_DIRECTION
Definition mirror.h:27
@ LEFT_RIGHT
Flip left to right (around the Y axis)
Definition mirror.h:28
@ TOP_BOTTOM
Flip top to bottom (around the X axis)
Definition mirror.h:29
const int scale
wxString result
Test unit parsing edge cases and error handling.
VECTOR2< int32_t > VECTOR2I
Definition vector2d.h:687