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

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