Audio plugin host https://kx.studio/carla
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

juce_Image.h 23KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2020 - Raw Material Software Limited
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. By using JUCE, you agree to the terms of both the JUCE 6 End-User License
  8. Agreement and JUCE Privacy Policy (both effective as of the 16th June 2020).
  9. End User License Agreement: www.juce.com/juce-6-licence
  10. Privacy Policy: www.juce.com/juce-privacy-policy
  11. Or: You may also use this code under the terms of the GPL v3 (see
  12. www.gnu.org/licenses).
  13. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  14. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  15. DISCLAIMED.
  16. ==============================================================================
  17. */
  18. namespace juce
  19. {
  20. class ImageType;
  21. class ImagePixelData;
  22. //==============================================================================
  23. /**
  24. Holds a fixed-size bitmap.
  25. The image is stored in either 24-bit RGB or 32-bit premultiplied-ARGB format.
  26. To draw into an image, create a Graphics object for it.
  27. e.g. @code
  28. // create a transparent 500x500 image..
  29. Image myImage (Image::RGB, 500, 500, true);
  30. Graphics g (myImage);
  31. g.setColour (Colours::red);
  32. g.fillEllipse (20, 20, 300, 200); // draws a red ellipse in our image.
  33. @endcode
  34. Other useful ways to create an image are with the ImageCache class, or the
  35. ImageFileFormat, which provides a way to load common image files.
  36. @see Graphics, ImageFileFormat, ImageCache, ImageConvolutionKernel
  37. @tags{Graphics}
  38. */
  39. class JUCE_API Image final
  40. {
  41. public:
  42. //==============================================================================
  43. /**
  44. */
  45. enum PixelFormat
  46. {
  47. UnknownFormat,
  48. RGB, /**<< each pixel is a 3-byte packed RGB colour value. For byte order, see the PixelRGB class. */
  49. ARGB, /**<< each pixel is a 4-byte ARGB premultiplied colour value. For byte order, see the PixelARGB class. */
  50. SingleChannel /**<< each pixel is a 1-byte alpha channel value. */
  51. };
  52. //==============================================================================
  53. /** Creates a null image. */
  54. Image() noexcept;
  55. /** Creates an image with a specified size and format.
  56. The image's internal type will be of the NativeImageType class - to specify a
  57. different type, use the other constructor, which takes an ImageType to use.
  58. @param format the preferred pixel format. Note that this is only a *hint* which
  59. is passed to the ImageType class - different ImageTypes may not support
  60. all formats, so may substitute e.g. ARGB for RGB.
  61. @param imageWidth the desired width of the image, in pixels - this value must be
  62. greater than zero (otherwise a width of 1 will be used)
  63. @param imageHeight the desired width of the image, in pixels - this value must be
  64. greater than zero (otherwise a height of 1 will be used)
  65. @param clearImage if true, the image will initially be cleared to black (if it's RGB)
  66. or transparent black (if it's ARGB). If false, the image may contain
  67. junk initially, so you need to make sure you overwrite it thoroughly.
  68. */
  69. Image (PixelFormat format, int imageWidth, int imageHeight, bool clearImage);
  70. /** Creates an image with a specified size and format.
  71. @param format the preferred pixel format. Note that this is only a *hint* which
  72. is passed to the ImageType class - different ImageTypes may not support
  73. all formats, so may substitute e.g. ARGB for RGB.
  74. @param imageWidth the desired width of the image, in pixels - this value must be
  75. greater than zero (otherwise a width of 1 will be used)
  76. @param imageHeight the desired width of the image, in pixels - this value must be
  77. greater than zero (otherwise a height of 1 will be used)
  78. @param clearImage if true, the image will initially be cleared to black (if it's RGB)
  79. or transparent black (if it's ARGB). If false, the image may contain
  80. junk initially, so you need to make sure you overwrite it thoroughly.
  81. @param type the type of image - this lets you specify the internal format that will
  82. be used to allocate and manage the image data.
  83. */
  84. Image (PixelFormat format, int imageWidth, int imageHeight, bool clearImage, const ImageType& type);
  85. /** Creates a shared reference to another image.
  86. This won't create a duplicate of the image - when Image objects are copied, they simply
  87. point to the same shared image data. To make sure that an Image object has its own unique,
  88. unshared internal data, call duplicateIfShared().
  89. */
  90. Image (const Image&) noexcept;
  91. /** Makes this image refer to the same underlying image as another object.
  92. This won't create a duplicate of the image - when Image objects are copied, they simply
  93. point to the same shared image data. To make sure that an Image object has its own unique,
  94. unshared internal data, call duplicateIfShared().
  95. */
  96. Image& operator= (const Image&);
  97. /** Move constructor */
  98. Image (Image&&) noexcept;
  99. /** Move assignment operator */
  100. Image& operator= (Image&&) noexcept;
  101. /** Destructor. */
  102. ~Image();
  103. /** Returns true if the two images are referring to the same internal, shared image. */
  104. bool operator== (const Image& other) const noexcept { return image == other.image; }
  105. /** Returns true if the two images are not referring to the same internal, shared image. */
  106. bool operator!= (const Image& other) const noexcept { return image != other.image; }
  107. /** Returns true if this image isn't null.
  108. If you create an Image with the default constructor, it has no size or content, and is null
  109. until you reassign it to an Image which contains some actual data.
  110. The isNull() method is the opposite of isValid().
  111. @see isNull
  112. */
  113. inline bool isValid() const noexcept { return image != nullptr; }
  114. /** Returns true if this image is not valid.
  115. If you create an Image with the default constructor, it has no size or content, and is null
  116. until you reassign it to an Image which contains some actual data.
  117. The isNull() method is the opposite of isValid().
  118. @see isValid
  119. */
  120. inline bool isNull() const noexcept { return image == nullptr; }
  121. //==============================================================================
  122. /** Returns the image's width (in pixels). */
  123. int getWidth() const noexcept;
  124. /** Returns the image's height (in pixels). */
  125. int getHeight() const noexcept;
  126. /** Returns a rectangle with the same size as this image.
  127. The rectangle's origin is always (0, 0).
  128. */
  129. Rectangle<int> getBounds() const noexcept;
  130. /** Returns the image's pixel format. */
  131. PixelFormat getFormat() const noexcept;
  132. /** True if the image's format is ARGB. */
  133. bool isARGB() const noexcept;
  134. /** True if the image's format is RGB. */
  135. bool isRGB() const noexcept;
  136. /** True if the image's format is a single-channel alpha map. */
  137. bool isSingleChannel() const noexcept;
  138. /** True if the image contains an alpha-channel. */
  139. bool hasAlphaChannel() const noexcept;
  140. //==============================================================================
  141. /** Clears a section of the image with a given colour.
  142. This won't do any alpha-blending - it just sets all pixels in the image to
  143. the given colour (which may be non-opaque if the image has an alpha channel).
  144. */
  145. void clear (const Rectangle<int>& area, Colour colourToClearTo = Colour (0x00000000));
  146. /** Returns a rescaled version of this image.
  147. A new image is returned which is a copy of this one, rescaled to the given size.
  148. Note that if the new size is identical to the existing image, this will just return
  149. a reference to the original image, and won't actually create a duplicate.
  150. */
  151. Image rescaled (int newWidth, int newHeight,
  152. Graphics::ResamplingQuality quality = Graphics::mediumResamplingQuality) const;
  153. /** Creates a copy of this image.
  154. Note that it's usually more efficient to use duplicateIfShared(), because it may not be necessary
  155. to copy an image if nothing else is using it.
  156. @see getReferenceCount
  157. */
  158. Image createCopy() const;
  159. /** Returns a version of this image with a different image format.
  160. A new image is returned which has been converted to the specified format.
  161. Note that if the new format is no different to the current one, this will just return
  162. a reference to the original image, and won't actually create a copy.
  163. */
  164. Image convertedToFormat (PixelFormat newFormat) const;
  165. /** Makes sure that no other Image objects share the same underlying data as this one.
  166. If no other Image objects refer to the same shared data as this one, this method has no
  167. effect. But if there are other references to the data, this will create a new copy of
  168. the data internally.
  169. Call this if you want to draw onto the image, but want to make sure that this doesn't
  170. affect any other code that may be sharing the same data.
  171. @see getReferenceCount
  172. */
  173. void duplicateIfShared();
  174. /** Returns an image which refers to a subsection of this image.
  175. This will not make a copy of the original - the new image will keep a reference to it, so that
  176. if the original image is changed, the contents of the subsection will also change. Likewise if you
  177. draw into the subimage, you'll also be drawing onto that area of the original image. Note that if
  178. you use operator= to make the original Image object refer to something else, the subsection image
  179. won't pick up this change, it'll remain pointing at the original.
  180. The area passed-in will be clipped to the bounds of this image, so this may return a smaller
  181. image than the area you asked for, or even a null image if the area was out-of-bounds.
  182. */
  183. Image getClippedImage (const Rectangle<int>& area) const;
  184. //==============================================================================
  185. /** Returns the colour of one of the pixels in the image.
  186. If the coordinates given are beyond the image's boundaries, this will
  187. return Colours::transparentBlack.
  188. @see setPixelAt, Image::BitmapData::getPixelColour
  189. */
  190. Colour getPixelAt (int x, int y) const;
  191. /** Sets the colour of one of the image's pixels.
  192. If the coordinates are beyond the image's boundaries, then nothing will happen.
  193. Note that this won't do any alpha-blending, it'll just replace the existing pixel
  194. with the given one. The colour's opacity will be ignored if this image doesn't have
  195. an alpha-channel.
  196. @see getPixelAt, Image::BitmapData::setPixelColour
  197. */
  198. void setPixelAt (int x, int y, Colour colour);
  199. /** Changes the opacity of a pixel.
  200. This only has an effect if the image has an alpha channel and if the
  201. given coordinates are inside the image's boundary.
  202. The multiplier must be in the range 0 to 1.0, and the current alpha
  203. at the given coordinates will be multiplied by this value.
  204. @see setPixelAt
  205. */
  206. void multiplyAlphaAt (int x, int y, float multiplier);
  207. /** Changes the overall opacity of the image.
  208. This will multiply the alpha value of each pixel in the image by the given
  209. amount (limiting the resulting alpha values between 0 and 255). This allows
  210. you to make an image more or less transparent.
  211. If the image doesn't have an alpha channel, this won't have any effect.
  212. */
  213. void multiplyAllAlphas (float amountToMultiplyBy);
  214. /** Changes all the colours to be shades of grey, based on their current luminosity.
  215. */
  216. void desaturate();
  217. //==============================================================================
  218. /** Retrieves a section of an image as raw pixel data, so it can be read or written to.
  219. You should only use this class as a last resort - messing about with the internals of
  220. an image is only recommended for people who really know what they're doing!
  221. A BitmapData object should be used as a temporary, stack-based object. Don't keep one
  222. hanging around while the image is being used elsewhere.
  223. Depending on the way the image class is implemented, this may create a temporary buffer
  224. which is copied back to the image when the object is deleted, or it may just get a pointer
  225. directly into the image's raw data.
  226. You can use the stride and data values in this class directly, but don't alter them!
  227. The actual format of the pixel data depends on the image's format - see Image::getFormat(),
  228. and the PixelRGB, PixelARGB and PixelAlpha classes for more info.
  229. */
  230. class JUCE_API BitmapData final
  231. {
  232. public:
  233. enum ReadWriteMode
  234. {
  235. readOnly,
  236. writeOnly,
  237. readWrite
  238. };
  239. BitmapData (Image& image, int x, int y, int w, int h, ReadWriteMode mode);
  240. BitmapData (const Image& image, int x, int y, int w, int h);
  241. BitmapData (const Image& image, ReadWriteMode mode);
  242. ~BitmapData();
  243. /** Returns a pointer to the start of a line in the image.
  244. The coordinate you provide here isn't checked, so it's the caller's responsibility to make
  245. sure it's not out-of-range.
  246. */
  247. inline uint8* getLinePointer (int y) const noexcept { return data + (size_t) y * (size_t) lineStride; }
  248. /** Returns a pointer to a pixel in the image.
  249. The coordinates you give here are not checked, so it's the caller's responsibility to make sure they're
  250. not out-of-range.
  251. */
  252. inline uint8* getPixelPointer (int x, int y) const noexcept { return data + (size_t) y * (size_t) lineStride + (size_t) x * (size_t) pixelStride; }
  253. /** Returns the colour of a given pixel.
  254. For performance reasons, this won't do any bounds-checking on the coordinates, so it's the caller's
  255. responsibility to make sure they're within the image's size.
  256. */
  257. Colour getPixelColour (int x, int y) const noexcept;
  258. /** Sets the colour of a given pixel.
  259. For performance reasons, this won't do any bounds-checking on the coordinates, so it's the caller's
  260. responsibility to make sure they're within the image's size.
  261. */
  262. void setPixelColour (int x, int y, Colour colour) const noexcept;
  263. /** Returns the size of the bitmap. */
  264. Rectangle<int> getBounds() const noexcept { return Rectangle<int> (width, height); }
  265. uint8* data; /**< The raw pixel data, packed according to the image's pixel format. */
  266. PixelFormat pixelFormat; /**< The format of the data. */
  267. int lineStride; /**< The number of bytes between each line. */
  268. int pixelStride; /**< The number of bytes between each pixel. */
  269. int width, height;
  270. //==============================================================================
  271. /** Used internally by custom image types to manage pixel data lifetime. */
  272. class BitmapDataReleaser
  273. {
  274. protected:
  275. BitmapDataReleaser() = default;
  276. public:
  277. virtual ~BitmapDataReleaser() = default;
  278. };
  279. std::unique_ptr<BitmapDataReleaser> dataReleaser;
  280. private:
  281. JUCE_DECLARE_NON_COPYABLE (BitmapData)
  282. };
  283. //==============================================================================
  284. /** Copies a section of the image to somewhere else within itself. */
  285. void moveImageSection (int destX, int destY,
  286. int sourceX, int sourceY,
  287. int width, int height);
  288. /** Creates a RectangleList containing rectangles for all non-transparent pixels
  289. of the image.
  290. @param result the list that will have the area added to it
  291. @param alphaThreshold for a semi-transparent image, any pixels whose alpha is
  292. above this level will be considered opaque
  293. */
  294. void createSolidAreaMask (RectangleList<int>& result, float alphaThreshold) const;
  295. //==============================================================================
  296. /** Returns a NamedValueSet that is attached to the image and which can be used for
  297. associating custom values with it.
  298. If this is a null image, this will return a null pointer.
  299. */
  300. NamedValueSet* getProperties() const;
  301. //==============================================================================
  302. /** Creates a context suitable for drawing onto this image.
  303. Don't call this method directly! It's used internally by the Graphics class.
  304. */
  305. std::unique_ptr<LowLevelGraphicsContext> createLowLevelContext() const;
  306. /** Returns the number of Image objects which are currently referring to the same internal
  307. shared image data.
  308. @see duplicateIfShared
  309. */
  310. int getReferenceCount() const noexcept;
  311. //==============================================================================
  312. /** @internal */
  313. ImagePixelData* getPixelData() const noexcept { return image.get(); }
  314. /** @internal */
  315. explicit Image (ReferenceCountedObjectPtr<ImagePixelData>) noexcept;
  316. /* A null Image object that can be used when you need to return an invalid image.
  317. @deprecated If you need a default-constructed var, just use Image() or {}.
  318. */
  319. JUCE_DEPRECATED_STATIC (static const Image null;)
  320. private:
  321. //==============================================================================
  322. ReferenceCountedObjectPtr<ImagePixelData> image;
  323. JUCE_LEAK_DETECTOR (Image)
  324. };
  325. //==============================================================================
  326. /**
  327. This is a base class for holding image data in implementation-specific ways.
  328. You may never need to use this class directly - it's used internally
  329. by the Image class to store the actual image data. To access pixel data directly,
  330. you should use Image::BitmapData rather than this class.
  331. ImagePixelData objects are created indirectly, by subclasses of ImageType.
  332. @see Image, ImageType
  333. @tags{Graphics}
  334. */
  335. class JUCE_API ImagePixelData : public ReferenceCountedObject
  336. {
  337. public:
  338. ImagePixelData (Image::PixelFormat, int width, int height);
  339. ~ImagePixelData() override;
  340. using Ptr = ReferenceCountedObjectPtr<ImagePixelData>;
  341. /** Creates a context that will draw into this image. */
  342. virtual std::unique_ptr<LowLevelGraphicsContext> createLowLevelContext() = 0;
  343. /** Creates a copy of this image. */
  344. virtual Ptr clone() = 0;
  345. /** Creates an instance of the type of this image. */
  346. virtual std::unique_ptr<ImageType> createType() const = 0;
  347. /** Initialises a BitmapData object. */
  348. virtual void initialiseBitmapData (Image::BitmapData&, int x, int y, Image::BitmapData::ReadWriteMode) = 0;
  349. /** Returns the number of Image objects which are currently referring to the same internal
  350. shared image data. This is different to the reference count as an instance of ImagePixelData
  351. can internally depend on another ImagePixelData via it's member variables. */
  352. virtual int getSharedCount() const noexcept;
  353. /** The pixel format of the image data. */
  354. const Image::PixelFormat pixelFormat;
  355. const int width, height;
  356. /** User-defined settings that are attached to this image.
  357. @see Image::getProperties().
  358. */
  359. NamedValueSet userData;
  360. //==============================================================================
  361. /** Used to receive callbacks for image data changes */
  362. struct Listener
  363. {
  364. virtual ~Listener() = default;
  365. virtual void imageDataChanged (ImagePixelData*) = 0;
  366. virtual void imageDataBeingDeleted (ImagePixelData*) = 0;
  367. };
  368. ListenerList<Listener> listeners;
  369. void sendDataChangeMessage();
  370. private:
  371. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ImagePixelData)
  372. };
  373. //==============================================================================
  374. /**
  375. This base class is for handlers that control a type of image manipulation format,
  376. e.g. an in-memory bitmap, an OpenGL image, CoreGraphics image, etc.
  377. @see SoftwareImageType, NativeImageType, OpenGLImageType
  378. @tags{Graphics}
  379. */
  380. class JUCE_API ImageType
  381. {
  382. public:
  383. ImageType();
  384. virtual ~ImageType();
  385. /** Creates a new image of this type, and the specified parameters. */
  386. virtual ImagePixelData::Ptr create (Image::PixelFormat, int width, int height, bool shouldClearImage) const = 0;
  387. /** Must return a unique number to identify this type. */
  388. virtual int getTypeID() const = 0;
  389. /** Returns an image which is a copy of the source image, but using this type of storage mechanism.
  390. For example, to make sure that an image is stored in-memory, you could use:
  391. @code myImage = SoftwareImageType().convert (myImage); @endcode
  392. */
  393. virtual Image convert (const Image& source) const;
  394. };
  395. //==============================================================================
  396. /**
  397. An image storage type which holds the pixels in-memory as a simple block of values.
  398. @see ImageType, NativeImageType
  399. @tags{Graphics}
  400. */
  401. class JUCE_API SoftwareImageType : public ImageType
  402. {
  403. public:
  404. SoftwareImageType();
  405. ~SoftwareImageType() override;
  406. ImagePixelData::Ptr create (Image::PixelFormat, int width, int height, bool clearImage) const override;
  407. int getTypeID() const override;
  408. };
  409. //==============================================================================
  410. /**
  411. An image storage type which holds the pixels using whatever is the default storage
  412. format on the current platform.
  413. @see ImageType, SoftwareImageType
  414. @tags{Graphics}
  415. */
  416. class JUCE_API NativeImageType : public ImageType
  417. {
  418. public:
  419. NativeImageType();
  420. ~NativeImageType() override;
  421. ImagePixelData::Ptr create (Image::PixelFormat, int width, int height, bool clearImage) const override;
  422. int getTypeID() const override;
  423. };
  424. } // namespace juce