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 (C) 2011-2024 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 <gr_basic.h>
28#include <math/util.h> // for KiROUND
29#include <memory> // for make_unique, unique_ptr
30#include <plotters/plotter.h>
31#include <richio.h>
32#include <wx/bitmap.h> // for wxBitmap
33#include <wx/mstream.h>
34#include <wx/stream.h> // for wxInputStream, wxOutputStream
35#include <wx/string.h> // for wxString
36#include <wx/wfstream.h> // for wxFileInputStream
37
38
39
41{
42 m_scale = 1.0; // 1.0 = original bitmap size
43 m_imageType = wxBITMAP_TYPE_INVALID;
44 m_bitmap = nullptr;
45 m_image = nullptr;
46 m_originalImage = nullptr;
47 m_ppi = 300; // the bitmap definition. the default is 300PPI
48 m_pixelSizeIu = 254000.0 / m_ppi; // a pixel size value OK for bitmaps using 300 PPI
49 // for Eeschema which uses currently 254000PPI
50 m_isMirroredX = false;
51 m_isMirroredY = false;
53}
54
55
57{
58 m_scale = aSchBitmap.m_scale;
59 m_ppi = aSchBitmap.m_ppi;
60 m_pixelSizeIu = aSchBitmap.m_pixelSizeIu;
61 m_isMirroredX = aSchBitmap.m_isMirroredX;
62 m_isMirroredY = aSchBitmap.m_isMirroredY;
63 m_rotation = aSchBitmap.m_rotation;
64 m_imageType = aSchBitmap.m_imageType;
65
66 m_image = nullptr;
67 m_bitmap = nullptr;
68 m_originalImage = nullptr;
69
70 if( aSchBitmap.m_image )
71 {
72 m_image = new wxImage( *aSchBitmap.m_image );
73 m_bitmap = new wxBitmap( *m_image );
74 m_originalImage = new wxImage( *aSchBitmap.m_originalImage );
75 m_imageType = aSchBitmap.m_imageType;
76 m_imageData = aSchBitmap.m_imageData;
77 m_imageId = aSchBitmap.m_imageId;
78 }
79}
80
81
82void BITMAP_BASE::rebuildBitmap( bool aResetID )
83{
84 if( m_bitmap )
85 delete m_bitmap;
86
87 m_bitmap = new wxBitmap( *m_image );
88
89 if( aResetID )
90 m_imageId = KIID();
91
92}
93
94
96{
97 // Todo: eventually we need to support dpi / scaling in both dimensions
98 int dpiX = m_originalImage->GetOptionInt( wxIMAGE_OPTION_RESOLUTIONX );
99
100 if( dpiX > 1 )
101 {
102 if( m_originalImage->GetOptionInt( wxIMAGE_OPTION_RESOLUTIONUNIT ) == wxIMAGE_RESOLUTION_CM )
103 m_ppi = KiROUND( dpiX * 2.54 );
104 else
105 m_ppi = dpiX;
106 }
107}
108
109
111{
112 *m_image = *aItem.m_image;
113 *m_bitmap = *aItem.m_bitmap;
115 m_imageId = aItem.m_imageId;
116 m_scale = aItem.m_scale;
117 m_ppi = aItem.m_ppi;
121 m_rotation = aItem.m_rotation;
122 m_imageType = aItem.m_imageType;
123 m_imageData = aItem.m_imageData;
124}
125
126
127bool BITMAP_BASE::ReadImageFile( wxInputStream& aInStream )
128{
129 // Store the original image data in m_imageData
130 size_t dataSize = aInStream.GetLength();
131 m_imageData.SetBufSize( dataSize );
132 aInStream.Read( m_imageData.GetData(), dataSize );
133 m_imageData.SetDataLen( dataSize );
134
135 std::unique_ptr<wxImage> new_image = std::make_unique<wxImage>();
136
137 // Load the image from the stream into new_image
138 wxMemoryInputStream mem_stream( m_imageData.GetData(), dataSize );
139 if( !new_image->LoadFile( mem_stream ) )
140 return false;
141
142 delete m_image;
143 m_imageType = new_image->GetType();
144 m_image = new_image.release();
145
146 // Create a new wxImage object from m_image
147 delete m_originalImage;
148 m_originalImage = new wxImage( *m_image );
149
151 updatePPI();
152
153 return true;
154}
155
156
157bool BITMAP_BASE::ReadImageFile( wxMemoryBuffer& aBuf )
158{
159 // Store the original image data in m_imageData
160 m_imageData = aBuf;
161
162 std::unique_ptr<wxImage> new_image = std::make_unique<wxImage>();
163
164 // Load the image from the buffer into new_image
165 wxMemoryInputStream mem_stream( m_imageData.GetData(), m_imageData.GetBufSize() );
166
167 if( !new_image->LoadFile( mem_stream ) )
168 return false;
169
170 delete m_image;
171 m_imageType = new_image->GetType();
172 m_image = new_image.release();
173
174 // Create a new wxImage object from m_image
175 delete m_originalImage;
176 m_originalImage = new wxImage( *m_image );
177
179 updatePPI();
180
181 return true;
182}
183
184
185bool BITMAP_BASE::ReadImageFile(const wxString& aFullFilename)
186{
187 wxFileInputStream file_stream(aFullFilename);
188
189 // Check if the file could be opened successfully
190 if (!file_stream.IsOk())
191 return false;
192
193 return ReadImageFile(file_stream);
194}
195
196
197bool BITMAP_BASE::SaveImageData( wxOutputStream& aOutStream ) const
198{
199 if( m_imageData.IsEmpty() )
200 {
201 // If m_imageData is empty, use wxImage::Save() method to write m_image contents to the stream.
202 wxBitmapType type = m_imageType == wxBITMAP_TYPE_JPEG ? wxBITMAP_TYPE_JPEG : wxBITMAP_TYPE_PNG;
203
204 if( !m_image->SaveFile( aOutStream, type ) )
205 {
206 return false;
207 }
208 }
209 else
210 {
211 // Write the contents of m_imageData to the stream.
212 aOutStream.Write( m_imageData.GetData(), m_imageData.GetBufSize() );
213 }
214
215 return true;
216}
217
218
219bool BITMAP_BASE::LoadLegacyData( LINE_READER& aLine, wxString& aErrorMsg )
220{
221 wxMemoryOutputStream stream;
222 char* line;
223
224 while( true )
225 {
226 if( !aLine.ReadLine() )
227 {
228 aErrorMsg = wxT("Unexpected end of data");
229 return false;
230 }
231
232 line = aLine.Line();
233
234 if( strncasecmp( line, "EndData", 4 ) == 0 )
235 {
236 // all the PNG date is read.
237 // We expect here m_image and m_bitmap are void
238 m_image = new wxImage();
239 wxMemoryInputStream istream( stream );
240 m_image->LoadFile( istream, wxBITMAP_TYPE_ANY );
241 m_bitmap = new wxBitmap( *m_image );
242 m_originalImage = new wxImage( *m_image );
244 break;
245 }
246
247 // Read PNG data, stored in hexadecimal,
248 // each byte = 2 hexadecimal digits and a space between 2 bytes
249 // and put it in memory stream buffer
250 int len = strlen( line );
251
252 for( ; len > 0; len -= 3, line += 3 )
253 {
254 int value = 0;
255
256 if( sscanf( line, "%X", &value ) == 1 )
257 stream.PutC( (char) value );
258 else
259 break;
260 }
261 }
262
263 return true;
264}
265
266
268{
269 BOX2I bbox;
270 VECTOR2I size = GetSize();
271
272 bbox.Inflate( size.x / 2, size.y / 2 );
273
274 return bbox;
275}
276
277
278void BITMAP_BASE::DrawBitmap( wxDC* aDC, const VECTOR2I& aPos,
279 const KIGFX::COLOR4D& aBackgroundColor ) const
280{
281 if( m_bitmap == nullptr )
282 return;
283
284 VECTOR2I pos = aPos;
285 VECTOR2I size = GetSize();
286
287 // This fixes a bug in OSX that should be fixed in the 3.0.3 version or later.
288 if( ( size.x == 0 ) || ( size.y == 0 ) )
289 return;
290
291 // To draw the bitmap, pos is the upper left corner position
292 pos.x -= size.x / 2;
293 pos.y -= size.y / 2;
294
295 double scale;
296 int logicalOriginX, logicalOriginY;
297 aDC->GetUserScale( &scale, &scale );
298 aDC->GetLogicalOrigin( &logicalOriginX, &logicalOriginY );
299
300 // We already have issues to draw a bitmap on the wxDC, depending on wxWidgets version.
301 // Now we have an issue on wxWidgets 3.1.6 to fix the clip area
302 // and the bitmap position when using TransformMatrix
303 // So for version == 3.1.6 do not use it
304 // Be carefull before changing the code.
305 bool useTransform = aDC->CanUseTransformMatrix();
306
307 wxAffineMatrix2D init_matrix = aDC->GetTransformMatrix();
308
309 // Note: clipping bitmap area was made to fix a minor issue in old versions of
310 // Kicad/wxWidgets (5.1 / wx 3.0)
311 // However SetClippingRegion creates a lot of issues (different ways to fix the
312 // position and size of the area, depending on wxWidget version)because it changes with
313 // each versions of wxWigets, so it is now disabled
314 // However the code is still here, just in case
315 // #define USE_CLIP_AREA
316
317 wxPoint clipAreaPos;
318
319 if( useTransform )
320 {
321 wxAffineMatrix2D matrix = aDC->GetTransformMatrix();
322 matrix.Translate( pos.x, pos.y );
323 matrix.Scale( GetScalingFactor(), GetScalingFactor() );
324 aDC->SetTransformMatrix( matrix );
325 // Needed on wx <= 3.1.5, and this is strange...
326 // Nevertheless, this code has problem (the bitmap is not seen)
327 // with wx version > 3.1.5
328 clipAreaPos.x = pos.x;
329 clipAreaPos.y = pos.y;
330
331 pos.x = pos.y = 0;
332 }
333 else
334 {
335 aDC->SetUserScale( scale * GetScalingFactor(), scale * GetScalingFactor() );
336 aDC->SetLogicalOrigin( logicalOriginX / GetScalingFactor(),
337 logicalOriginY / GetScalingFactor() );
338
339 pos.x = KiROUND( pos.x / GetScalingFactor() );
340 pos.y = KiROUND( pos.y / GetScalingFactor() );
341 size.x = KiROUND( size.x / GetScalingFactor() );
342 size.y = KiROUND( size.y / GetScalingFactor() );
343 clipAreaPos.x = pos.x;
344 clipAreaPos.y = pos.y;
345 }
346
347 #ifdef USE_CLIP_AREA
348 aDC->DestroyClippingRegion();
349 aDC->SetClippingRegion( clipAreaPos, wxSize( size.x, size.y ) );
350 #endif
351
352 if( aBackgroundColor != COLOR4D::UNSPECIFIED && m_bitmap->HasAlpha() )
353 {
354 // Most printers don't support transparent images properly,
355 // so blend the image with background color.
356
357 int w = m_bitmap->GetWidth();
358 int h = m_bitmap->GetHeight();
359
360 wxImage image( w, h );
361 wxColour bgColor = aBackgroundColor.ToColour();
362
363 image.SetRGB( wxRect( 0, 0, w, h ), bgColor.Red(), bgColor.Green(), bgColor.Blue() );
364 image.Paste( m_bitmap->ConvertToImage(), 0, 0, wxIMAGE_ALPHA_BLEND_COMPOSE );
365
367 image = image.ConvertToGreyscale();
368
369 aDC->DrawBitmap( wxBitmap( image ), pos.x, pos.y, true );
370 }
371 else if( GetGRForceBlackPenState() )
372 {
373 wxBitmap result( m_bitmap->ConvertToImage().ConvertToGreyscale() );
374 aDC->DrawBitmap( result, pos.x, pos.y, true );
375 }
376 else
377 {
378 aDC->DrawBitmap( *m_bitmap, pos.x, pos.y, true );
379 }
380
381 if( useTransform )
382 aDC->SetTransformMatrix( init_matrix );
383 else
384 {
385 aDC->SetUserScale( scale, scale );
386 aDC->SetLogicalOrigin( logicalOriginX, logicalOriginY );
387 }
388
389 #ifdef USE_CLIP_AREA
390 aDC->DestroyClippingRegion();
391 #endif
392}
393
394
396{
397 VECTOR2I size;
398
399 if( m_bitmap )
400 {
401 size.x = m_bitmap->GetWidth();
402 size.y = m_bitmap->GetHeight();
403
404 size.x = KiROUND( size.x * GetScalingFactor() );
405 size.y = KiROUND( size.y * GetScalingFactor() );
406 }
407
408 return size;
409}
410
411
413{
414 if( m_image )
415 {
416 // wxImage::Mirror() clear some parameters of the original image.
417 // We need to restore them, especially resolution and unit, to be
418 // sure image parameters saved in file are the right parameters, not
419 // the defualt values
420 int resX = m_image->GetOptionInt( wxIMAGE_OPTION_RESOLUTIONX );
421 int resY = m_image->GetOptionInt( wxIMAGE_OPTION_RESOLUTIONY );
422 int unit = m_image->GetOptionInt( wxIMAGE_OPTION_RESOLUTIONUNIT );
423
424 *m_image = m_image->Mirror( aFlipDirection == FLIP_DIRECTION::LEFT_RIGHT );
425
426 m_image->SetOption( wxIMAGE_OPTION_RESOLUTIONUNIT , unit);
427 m_image->SetOption( wxIMAGE_OPTION_RESOLUTIONX, resX);
428 m_image->SetOption( wxIMAGE_OPTION_RESOLUTIONY, resY);
429
430 if( aFlipDirection == FLIP_DIRECTION::TOP_BOTTOM )
432 else
434
435 rebuildBitmap( false );
437 }
438}
439
440
441void BITMAP_BASE::Rotate( bool aRotateCCW )
442{
443 if( m_image )
444 {
445 // wxImage::Rotate90() clear some parameters of the original image.
446 // We need to restore them, especially resolution and unit, to be
447 // sure image parameters saved in file are the right parameters, not
448 // the defualt values
449 int resX = m_image->GetOptionInt( wxIMAGE_OPTION_RESOLUTIONX );
450 int resY = m_image->GetOptionInt( wxIMAGE_OPTION_RESOLUTIONY );
451 int unit = m_image->GetOptionInt( wxIMAGE_OPTION_RESOLUTIONUNIT );
452
453 *m_image = m_image->Rotate90( aRotateCCW );
454
455 m_image->SetOption( wxIMAGE_OPTION_RESOLUTIONUNIT , unit);
456 m_image->SetOption( wxIMAGE_OPTION_RESOLUTIONX, resX);
457 m_image->SetOption( wxIMAGE_OPTION_RESOLUTIONY, resY);
458
459 m_rotation += ( aRotateCCW ? ANGLE_90 : -ANGLE_90 );
460 rebuildBitmap( false );
462 }
463}
464
465
467{
468 if( m_image )
469 {
470 *m_image = m_image->ConvertToGreyscale();
471 *m_originalImage = m_originalImage->ConvertToGreyscale();
474 }
475}
476
477
478void BITMAP_BASE::PlotImage( PLOTTER* aPlotter, const VECTOR2I& aPos,
479 const COLOR4D& aDefaultColor,
480 int aDefaultPensize ) const
481{
482 if( m_image == nullptr )
483 return;
484
485 // These 2 lines are useful only for plotters that cannot plot a bitmap
486 // and plot a rectangle instead of.
487 aPlotter->SetColor( aDefaultColor );
488 aPlotter->SetCurrentLineWidth( aDefaultPensize );
489 aPlotter->PlotImage( *m_image, aPos, GetScalingFactor() );
490}
491
492
494{
495 if( m_image )
496 {
497 wxMemoryOutputStream stream;
498 wxBitmapType type = m_imageType == wxBITMAP_TYPE_JPEG ? wxBITMAP_TYPE_JPEG : wxBITMAP_TYPE_PNG;
499
500 if( !m_image->SaveFile( stream, type ) )
501 return;
502
503 m_imageData.GetWriteBuf( stream.GetLength() );
504 stream.CopyTo( m_imageData.GetData(), stream.GetLength() );
505 m_imageData.SetDataLen( stream.GetLength() );
506 }
507}
constexpr BOX2I KiROUND(const BOX2D &aBoxD)
Definition: box2.h:990
This class handle bitmap images in KiCad.
Definition: bitmap_base.h:49
wxMemoryBuffer m_imageData
Definition: bitmap_base.h:262
void Rotate(bool aRotateCCW)
Rotate image CW or CCW.
bool LoadLegacyData(LINE_READER &aLine, wxString &aErrorMsg)
Load an image data saved by #SaveData.
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.
void updatePPI()
Definition: bitmap_base.cpp:95
const BOX2I GetBoundingBox() const
Return the orthogonal, bounding box of this object for display purposes.
bool m_isMirroredY
Definition: bitmap_base.h:275
bool m_isMirroredX
Definition: bitmap_base.h:274
void ImportData(BITMAP_BASE &aItem)
Copy aItem image to this object and update m_bitmap.
KIID m_imageId
Definition: bitmap_base.h:273
bool SaveImageData(wxOutputStream &aOutStream) const
Write the bitmap data to aOutStream.
wxImage * m_originalImage
Definition: bitmap_base.h:266
void rebuildBitmap(bool aResetID=true)
Definition: bitmap_base.cpp:82
wxBitmapType m_imageType
Definition: bitmap_base.h:263
wxBitmap * m_bitmap
Definition: bitmap_base.h:267
void ConvertToGreyscale()
void UpdateImageDataBuffer()
Resets the image data buffer using the current image data.
bool ReadImageFile(const wxString &aFullFilename)
Reads and stores in memory an image file.
wxImage * m_image
Definition: bitmap_base.h:265
double m_scale
Definition: bitmap_base.h:260
double m_pixelSizeIu
Definition: bitmap_base.h:268
void DrawBitmap(wxDC *aDC, const VECTOR2I &aPos, const KIGFX::COLOR4D &aBackgroundColor=KIGFX::COLOR4D::UNSPECIFIED) const
BITMAP_BASE(const VECTOR2I &pos=VECTOR2I(0, 0))
Definition: bitmap_base.cpp:40
VECTOR2I GetSize() const
EDA_ANGLE m_rotation
Definition: bitmap_base.h:276
constexpr BOX2< Vec > & Inflate(coord_type dx, coord_type dy)
Inflates the rectangle horizontally by dx and vertically by dy.
Definition: box2.h:558
A color representation with 4 components: red, green, blue, alpha.
Definition: color4d.h:104
wxColour ToColour() const
Definition: color4d.cpp:220
Definition: kiid.h:49
An abstract class from which implementation specific LINE_READERs may be derived to read single lines...
Definition: richio.h:93
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:129
Base plotter engine class.
Definition: plotter.h:105
virtual void PlotImage(const wxImage &aImage, const VECTOR2I &aPos, double aScaleFactor)
Only PostScript plotters can plot bitmaps.
Definition: plotter.cpp:258
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:401
static constexpr EDA_ANGLE ANGLE_90
Definition: eda_angle.h:403
bool GetGRForceBlackPenState(void)
Definition: gr_basic.cpp:165
FLIP_DIRECTION
Definition: mirror.h:27
const int scale