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.

558 lines
23KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2022 - 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 7 End-User License
  8. Agreement and JUCE Privacy Policy.
  9. End User License Agreement: www.juce.com/juce-7-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. size_t size; /**< The number of valid/allocated bytes after data. May be smaller than "lineStride * height" if this is a section of a larger image. */
  267. PixelFormat pixelFormat; /**< The format of the data. */
  268. int lineStride; /**< The number of bytes between each line. */
  269. int pixelStride; /**< The number of bytes between each pixel. */
  270. int width, height;
  271. //==============================================================================
  272. /** Used internally by custom image types to manage pixel data lifetime. */
  273. class BitmapDataReleaser
  274. {
  275. protected:
  276. BitmapDataReleaser() = default;
  277. public:
  278. virtual ~BitmapDataReleaser() = default;
  279. };
  280. std::unique_ptr<BitmapDataReleaser> dataReleaser;
  281. private:
  282. JUCE_DECLARE_NON_COPYABLE (BitmapData)
  283. };
  284. //==============================================================================
  285. /** Copies a section of the image to somewhere else within itself. */
  286. void moveImageSection (int destX, int destY,
  287. int sourceX, int sourceY,
  288. int width, int height);
  289. /** Creates a RectangleList containing rectangles for all non-transparent pixels
  290. of the image.
  291. @param result the list that will have the area added to it
  292. @param alphaThreshold for a semi-transparent image, any pixels whose alpha is
  293. above this level will be considered opaque
  294. */
  295. void createSolidAreaMask (RectangleList<int>& result, float alphaThreshold) const;
  296. //==============================================================================
  297. /** Returns a NamedValueSet that is attached to the image and which can be used for
  298. associating custom values with it.
  299. If this is a null image, this will return a null pointer.
  300. */
  301. NamedValueSet* getProperties() const;
  302. //==============================================================================
  303. /** Creates a context suitable for drawing onto this image.
  304. Don't call this method directly! It's used internally by the Graphics class.
  305. */
  306. std::unique_ptr<LowLevelGraphicsContext> createLowLevelContext() const;
  307. /** Returns the number of Image objects which are currently referring to the same internal
  308. shared image data.
  309. @see duplicateIfShared
  310. */
  311. int getReferenceCount() const noexcept;
  312. //==============================================================================
  313. /** @internal */
  314. ImagePixelData* getPixelData() const noexcept { return image.get(); }
  315. /** @internal */
  316. explicit Image (ReferenceCountedObjectPtr<ImagePixelData>) noexcept;
  317. //==============================================================================
  318. #if JUCE_ALLOW_STATIC_NULL_VARIABLES && ! defined (DOXYGEN)
  319. /* A null Image object that can be used when you need to return an invalid image. */
  320. [[deprecated ("If you need a default-constructed var, just use Image() or {}.")]]
  321. static const Image null;
  322. #endif
  323. private:
  324. //==============================================================================
  325. ReferenceCountedObjectPtr<ImagePixelData> image;
  326. JUCE_LEAK_DETECTOR (Image)
  327. };
  328. //==============================================================================
  329. /**
  330. This is a base class for holding image data in implementation-specific ways.
  331. You may never need to use this class directly - it's used internally
  332. by the Image class to store the actual image data. To access pixel data directly,
  333. you should use Image::BitmapData rather than this class.
  334. ImagePixelData objects are created indirectly, by subclasses of ImageType.
  335. @see Image, ImageType
  336. @tags{Graphics}
  337. */
  338. class JUCE_API ImagePixelData : public ReferenceCountedObject
  339. {
  340. public:
  341. ImagePixelData (Image::PixelFormat, int width, int height);
  342. ~ImagePixelData() override;
  343. using Ptr = ReferenceCountedObjectPtr<ImagePixelData>;
  344. /** Creates a context that will draw into this image. */
  345. virtual std::unique_ptr<LowLevelGraphicsContext> createLowLevelContext() = 0;
  346. /** Creates a copy of this image. */
  347. virtual Ptr clone() = 0;
  348. /** Creates an instance of the type of this image. */
  349. virtual std::unique_ptr<ImageType> createType() const = 0;
  350. /** Initialises a BitmapData object. */
  351. virtual void initialiseBitmapData (Image::BitmapData&, int x, int y, Image::BitmapData::ReadWriteMode) = 0;
  352. /** Returns the number of Image objects which are currently referring to the same internal
  353. shared image data. This is different to the reference count as an instance of ImagePixelData
  354. can internally depend on another ImagePixelData via it's member variables. */
  355. virtual int getSharedCount() const noexcept;
  356. /** The pixel format of the image data. */
  357. const Image::PixelFormat pixelFormat;
  358. const int width, height;
  359. /** User-defined settings that are attached to this image.
  360. @see Image::getProperties().
  361. */
  362. NamedValueSet userData;
  363. //==============================================================================
  364. /** Used to receive callbacks for image data changes */
  365. struct Listener
  366. {
  367. virtual ~Listener() = default;
  368. virtual void imageDataChanged (ImagePixelData*) = 0;
  369. virtual void imageDataBeingDeleted (ImagePixelData*) = 0;
  370. };
  371. ListenerList<Listener> listeners;
  372. void sendDataChangeMessage();
  373. private:
  374. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ImagePixelData)
  375. };
  376. //==============================================================================
  377. /**
  378. This base class is for handlers that control a type of image manipulation format,
  379. e.g. an in-memory bitmap, an OpenGL image, CoreGraphics image, etc.
  380. @see SoftwareImageType, NativeImageType, OpenGLImageType
  381. @tags{Graphics}
  382. */
  383. class JUCE_API ImageType
  384. {
  385. public:
  386. ImageType();
  387. virtual ~ImageType();
  388. /** Creates a new image of this type, and the specified parameters. */
  389. virtual ImagePixelData::Ptr create (Image::PixelFormat, int width, int height, bool shouldClearImage) const = 0;
  390. /** Must return a unique number to identify this type. */
  391. virtual int getTypeID() const = 0;
  392. /** Returns an image which is a copy of the source image, but using this type of storage mechanism.
  393. For example, to make sure that an image is stored in-memory, you could use:
  394. @code myImage = SoftwareImageType().convert (myImage); @endcode
  395. */
  396. virtual Image convert (const Image& source) const;
  397. };
  398. //==============================================================================
  399. /**
  400. An image storage type which holds the pixels in-memory as a simple block of values.
  401. @see ImageType, NativeImageType
  402. @tags{Graphics}
  403. */
  404. class JUCE_API SoftwareImageType : public ImageType
  405. {
  406. public:
  407. SoftwareImageType();
  408. ~SoftwareImageType() override;
  409. ImagePixelData::Ptr create (Image::PixelFormat, int width, int height, bool clearImage) const override;
  410. int getTypeID() const override;
  411. };
  412. //==============================================================================
  413. /**
  414. An image storage type which holds the pixels using whatever is the default storage
  415. format on the current platform.
  416. @see ImageType, SoftwareImageType
  417. @tags{Graphics}
  418. */
  419. class JUCE_API NativeImageType : public ImageType
  420. {
  421. public:
  422. NativeImageType();
  423. ~NativeImageType() override;
  424. ImagePixelData::Ptr create (Image::PixelFormat, int width, int height, bool clearImage) const override;
  425. int getTypeID() const override;
  426. };
  427. } // namespace juce