├── .github
├── afdian.jpg
└── workflows
│ └── test.yml
├── .gitignore
├── CHANGELOG.md
├── LICENSE
├── README.md
├── build.gradle.kts
├── example
├── 90446978_p0.png
├── 90487779_p0.png
├── Osu.svg
├── cssxsh.svg
├── dear.gif
├── face.png
├── osu-logo-triangles.svg
├── osu-logo-white.svg
├── sprite.png
├── style.test.jpg
└── zzkia.jpg
├── gradle.properties
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── settings.gradle.kts
└── src
├── main
├── kotlin
│ └── xyz
│ │ └── cssxsh
│ │ ├── gif
│ │ ├── Ditherer.kt
│ │ ├── Encoder.kt
│ │ ├── Frame.kt
│ │ ├── Library.kt
│ │ ├── Quantizer.kt
│ │ └── Version.kt
│ │ ├── mirai
│ │ └── skia
│ │ │ ├── MiraiSkiaDownloader.kt
│ │ │ ├── MiraiSkiaPlugin.kt
│ │ │ ├── SkiaExternalResource.kt
│ │ │ └── SkiaToMirai.kt
│ │ └── skia
│ │ ├── Canvas.kt
│ │ ├── Example.kt
│ │ ├── Font.kt
│ │ ├── FontUtils.kt
│ │ ├── Mosaic.kt
│ │ ├── SVGDOM.kt
│ │ ├── Style.kt
│ │ └── gif
│ │ ├── ApplicationExtension.kt
│ │ ├── AtkinsonDitherer.kt
│ │ ├── ColorTable.kt
│ │ ├── GIFBuilder.kt
│ │ ├── GIFDsl.kt
│ │ ├── GraphicControlExtension.kt
│ │ ├── ImageDescriptor.kt
│ │ ├── LZWEncoder.kt
│ │ ├── LogicalScreenDescriptor.kt
│ │ └── OctTreeQuantizer.kt
└── resources
│ └── META-INF
│ └── services
│ └── net.mamoe.mirai.console.plugin.jvm.JvmPlugin
└── test
├── kotlin
└── xyz
│ └── cssxsh
│ ├── gif
│ └── EncoderTest.kt
│ └── skia
│ ├── ExampleKtTest.kt
│ └── StyleUtilsTest.kt
└── resources
└── META-INF
└── services
└── org.slf4j.spi.SLF4JServiceProvider
/.github/afdian.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cssxsh/mirai-skia-plugin/0a36163cc6d3dcf667365eabd27b9b17d0dc67a7/.github/afdian.jpg
--------------------------------------------------------------------------------
/.github/workflows/test.yml:
--------------------------------------------------------------------------------
1 | name: Test
2 | on:
3 | push:
4 | paths-ignore:
5 | - '**/*.md'
6 | pull_request:
7 | paths-ignore:
8 | - '**/*.md'
9 |
10 | jobs:
11 | test:
12 | runs-on: ${{ matrix.os }}
13 | strategy:
14 | fail-fast: false
15 | matrix:
16 | os:
17 | - windows-latest
18 | - macos-latest
19 | - ubuntu-latest
20 | steps:
21 | - name: Checkout
22 | uses: actions/checkout@v3
23 |
24 | - name: Setup JDK 11
25 | uses: actions/setup-java@v3
26 | with:
27 | distribution: 'adopt'
28 | java-version: '11'
29 |
30 | - name: chmod -R 777 *
31 | run: chmod -R 777 *
32 |
33 | - name: Assemble
34 | run: ./gradlew assemble --scan
35 |
36 | - name: SkiaExampleKtTest
37 | run: ./gradlew test --tests "xyz.cssxsh.skia.ExampleKtTest" --scan --info
38 |
39 | - name: GifEncoderTest
40 | run: ./gradlew test --tests "xyz.cssxsh.gif.EncoderTest" --scan --info
41 |
42 | - name: StyleUtilsTest
43 | run: ./gradlew test --tests "xyz.cssxsh.skia.StyleUtilsTest" --scan --info
44 |
45 | - name: Upload Run Result
46 | uses: actions/upload-artifact@v3
47 | with:
48 | name: run-${{ matrix.os }}-result
49 | path: |
50 | run/*
51 | !run/fonts/*
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # User-specific stuff
2 | .idea/
3 |
4 | *.iml
5 | *.ipr
6 | *.iws
7 |
8 | # IntelliJ
9 | out/
10 | # mpeltonen/sbt-idea plugin
11 | .idea_modules/
12 |
13 | # JIRA plugin
14 | atlassian-ide-plugin.xml
15 |
16 | # Compiled class file
17 | *.class
18 |
19 | # Log file
20 | *.log
21 |
22 | # BlueJ files
23 | *.ctxt
24 |
25 | # Package Files #
26 | *.jar
27 | *.war
28 | *.nar
29 | *.ear
30 | *.zip
31 | *.tar.gz
32 | *.rar
33 |
34 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
35 | hs_err_pid*
36 |
37 | *~
38 |
39 | # temporary files which can be created if a process still has a handle open of a deleted file
40 | .fuse_hidden*
41 |
42 | # KDE directory preferences
43 | .directory
44 |
45 | # Linux trash folder which might appear on any partition or disk
46 | .Trash-*
47 |
48 | # .nfs files are created when an open file is removed but is still being accessed
49 | .nfs*
50 |
51 | # General
52 | .DS_Store
53 | .AppleDouble
54 | .LSOverride
55 |
56 | # Icon must end with two \r
57 | Icon
58 |
59 | # Thumbnails
60 | ._*
61 |
62 | # Files that might appear in the root of a volume
63 | .DocumentRevisions-V100
64 | .fseventsd
65 | .Spotlight-V100
66 | .TemporaryItems
67 | .Trashes
68 | .VolumeIcon.icns
69 | .com.apple.timemachine.donotpresent
70 |
71 | # Directories potentially created on remote AFP share
72 | .AppleDB
73 | .AppleDesktop
74 | Network Trash Folder
75 | Temporary Items
76 | .apdisk
77 |
78 | # Windows thumbnail cache files
79 | Thumbs.db
80 | Thumbs.db:encryptable
81 | ehthumbs.db
82 | ehthumbs_vista.db
83 |
84 | # Dump file
85 | *.stackdump
86 |
87 | # Folder config file
88 | [Dd]esktop.ini
89 |
90 | # Recycle Bin used on file shares
91 | $RECYCLE.BIN/
92 |
93 | # Windows Installer files
94 | *.cab
95 | *.msi
96 | *.msix
97 | *.msm
98 | *.msp
99 |
100 | # Windows shortcuts
101 | *.lnk
102 |
103 | .gradle
104 | build/
105 |
106 | # Ignore Gradle GUI config
107 | gradle-app.setting
108 |
109 | # Cache of project
110 | .gradletasknamecache
111 |
112 | **/build/
113 |
114 | # Common working directory
115 | run/
116 |
117 | # Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored)
118 | !gradle-wrapper.jar
119 |
120 |
121 | # Local Test Launch point
122 | src/test/kotlin/RunTerminal.kt
123 |
124 | # Mirai console files with direct bootstrap
125 | /config
126 | /data
127 | /plugins
128 | /bots
129 |
130 | # Local Test Launch Point working directory
131 | /debug-sandbox
132 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | ## 1.3.1 (23/02/18)
2 |
3 | 1. fix: download filename
4 | 2. update: skiko 0.7.58
5 | 3. update: commons-compress 1.23.0
6 | 4. update: jsoup 1.16.1
7 | 5. feat: match noto color emoji
8 | 6. fix: android-arm64 download
9 |
10 | ## 1.3.1 (23/02/18)
11 |
12 | 1. update: skiko 0.7.54
13 | 2. update: jsoup 1.15.4
14 | 3. fix: download fonts
15 |
16 | ## 1.3.0 (23/02/18)
17 |
18 | 1. update: skiko 0.7.50
19 | 2. fix: cn download
20 | 3. feat: ci save result
21 | 4. fix: example font
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU AFFERO GENERAL PUBLIC LICENSE
2 | Version 3, 19 November 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU Affero General Public License is a free, copyleft license for
11 | software and other kinds of works, specifically designed to ensure
12 | cooperation with the community in the case of network server software.
13 |
14 | The licenses for most software and other practical works are designed
15 | to take away your freedom to share and change the works. By contrast,
16 | our General Public Licenses are intended to guarantee your freedom to
17 | share and change all versions of a program--to make sure it remains free
18 | software for all its users.
19 |
20 | When we speak of free software, we are referring to freedom, not
21 | price. Our General Public Licenses are designed to make sure that you
22 | have the freedom to distribute copies of free software (and charge for
23 | them if you wish), that you receive source code or can get it if you
24 | want it, that you can change the software or use pieces of it in new
25 | free programs, and that you know you can do these things.
26 |
27 | Developers that use our General Public Licenses protect your rights
28 | with two steps: (1) assert copyright on the software, and (2) offer
29 | you this License which gives you legal permission to copy, distribute
30 | and/or modify the software.
31 |
32 | A secondary benefit of defending all users' freedom is that
33 | improvements made in alternate versions of the program, if they
34 | receive widespread use, become available for other developers to
35 | incorporate. Many developers of free software are heartened and
36 | encouraged by the resulting cooperation. However, in the case of
37 | software used on network servers, this result may fail to come about.
38 | The GNU General Public License permits making a modified version and
39 | letting the public access it on a server without ever releasing its
40 | source code to the public.
41 |
42 | The GNU Affero General Public License is designed specifically to
43 | ensure that, in such cases, the modified source code becomes available
44 | to the community. It requires the operator of a network server to
45 | provide the source code of the modified version running there to the
46 | users of that server. Therefore, public use of a modified version, on
47 | a publicly accessible server, gives the public access to the source
48 | code of the modified version.
49 |
50 | An older license, called the Affero General Public License and
51 | published by Affero, was designed to accomplish similar goals. This is
52 | a different license, not a version of the Affero GPL, but Affero has
53 | released a new version of the Affero GPL which permits relicensing under
54 | this license.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | TERMS AND CONDITIONS
60 |
61 | 0. Definitions.
62 |
63 | "This License" refers to version 3 of the GNU Affero General Public License.
64 |
65 | "Copyright" also means copyright-like laws that apply to other kinds of
66 | works, such as semiconductor masks.
67 |
68 | "The Program" refers to any copyrightable work licensed under this
69 | License. Each licensee is addressed as "you". "Licensees" and
70 | "recipients" may be individuals or organizations.
71 |
72 | To "modify" a work means to copy from or adapt all or part of the work
73 | in a fashion requiring copyright permission, other than the making of an
74 | exact copy. The resulting work is called a "modified version" of the
75 | earlier work or a work "based on" the earlier work.
76 |
77 | A "covered work" means either the unmodified Program or a work based
78 | on the Program.
79 |
80 | To "propagate" a work means to do anything with it that, without
81 | permission, would make you directly or secondarily liable for
82 | infringement under applicable copyright law, except executing it on a
83 | computer or modifying a private copy. Propagation includes copying,
84 | distribution (with or without modification), making available to the
85 | public, and in some countries other activities as well.
86 |
87 | To "convey" a work means any kind of propagation that enables other
88 | parties to make or receive copies. Mere interaction with a user through
89 | a computer network, with no transfer of a copy, is not conveying.
90 |
91 | An interactive user interface displays "Appropriate Legal Notices"
92 | to the extent that it includes a convenient and prominently visible
93 | feature that (1) displays an appropriate copyright notice, and (2)
94 | tells the user that there is no warranty for the work (except to the
95 | extent that warranties are provided), that licensees may convey the
96 | work under this License, and how to view a copy of this License. If
97 | the interface presents a list of user commands or options, such as a
98 | menu, a prominent item in the list meets this criterion.
99 |
100 | 1. Source Code.
101 |
102 | The "source code" for a work means the preferred form of the work
103 | for making modifications to it. "Object code" means any non-source
104 | form of a work.
105 |
106 | A "Standard Interface" means an interface that either is an official
107 | standard defined by a recognized standards body, or, in the case of
108 | interfaces specified for a particular programming language, one that
109 | is widely used among developers working in that language.
110 |
111 | The "System Libraries" of an executable work include anything, other
112 | than the work as a whole, that (a) is included in the normal form of
113 | packaging a Major Component, but which is not part of that Major
114 | Component, and (b) serves only to enable use of the work with that
115 | Major Component, or to implement a Standard Interface for which an
116 | implementation is available to the public in source code form. A
117 | "Major Component", in this context, means a major essential component
118 | (kernel, window system, and so on) of the specific operating system
119 | (if any) on which the executable work runs, or a compiler used to
120 | produce the work, or an object code interpreter used to mirai it.
121 |
122 | The "Corresponding Source" for a work in object code form means all
123 | the source code needed to generate, install, and (for an executable
124 | work) mirai the object code and to modify the work, including scripts to
125 | control those activities. However, it does not include the work's
126 | System Libraries, or general-purpose tools or generally available free
127 | programs which are used unmodified in performing those activities but
128 | which are not part of the work. For example, Corresponding Source
129 | includes interface definition files associated with source files for
130 | the work, and the source code for shared libraries and dynamically
131 | linked subprograms that the work is specifically designed to require,
132 | such as by intimate data communication or control flow between those
133 | subprograms and other parts of the work.
134 |
135 | The Corresponding Source need not include anything that users
136 | can regenerate automatically from other parts of the Corresponding
137 | Source.
138 |
139 | The Corresponding Source for a work in source code form is that
140 | same work.
141 |
142 | 2. Basic Permissions.
143 |
144 | All rights granted under this License are granted for the term of
145 | copyright on the Program, and are irrevocable provided the stated
146 | conditions are met. This License explicitly affirms your unlimited
147 | permission to mirai the unmodified Program. The output from running a
148 | covered work is covered by this License only if the output, given its
149 | content, constitutes a covered work. This License acknowledges your
150 | rights of fair use or other equivalent, as provided by copyright law.
151 |
152 | You may make, mirai and propagate covered works that you do not
153 | convey, without conditions so long as your license otherwise remains
154 | in force. You may convey covered works to others for the sole purpose
155 | of having them make modifications exclusively for you, or provide you
156 | with facilities for running those works, provided that you comply with
157 | the terms of this License in conveying all material for which you do
158 | not control copyright. Those thus making or running the covered works
159 | for you must do so exclusively on your behalf, under your direction
160 | and control, on terms that prohibit them from making any copies of
161 | your copyrighted material outside their relationship with you.
162 |
163 | Conveying under any other circumstances is permitted solely under
164 | the conditions stated below. Sublicensing is not allowed; section 10
165 | makes it unnecessary.
166 |
167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168 |
169 | No covered work shall be deemed part of an effective technological
170 | measure under any applicable law fulfilling obligations under article
171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
172 | similar laws prohibiting or restricting circumvention of such
173 | measures.
174 |
175 | When you convey a covered work, you waive any legal power to forbid
176 | circumvention of technological measures to the extent such circumvention
177 | is effected by exercising rights under this License with respect to
178 | the covered work, and you disclaim any intention to limit operation or
179 | modification of the work as a means of enforcing, against the work's
180 | users, your or third parties' legal rights to forbid circumvention of
181 | technological measures.
182 |
183 | 4. Conveying Verbatim Copies.
184 |
185 | You may convey verbatim copies of the Program's source code as you
186 | receive it, in any medium, provided that you conspicuously and
187 | appropriately publish on each copy an appropriate copyright notice;
188 | keep intact all notices stating that this License and any
189 | non-permissive terms added in accord with section 7 apply to the code;
190 | keep intact all notices of the absence of any warranty; and give all
191 | recipients a copy of this License along with the Program.
192 |
193 | You may charge any price or no price for each copy that you convey,
194 | and you may offer support or warranty protection for a fee.
195 |
196 | 5. Conveying Modified Source Versions.
197 |
198 | You may convey a work based on the Program, or the modifications to
199 | produce it from the Program, in the form of source code under the
200 | terms of section 4, provided that you also meet all of these conditions:
201 |
202 | a) The work must carry prominent notices stating that you modified
203 | it, and giving a relevant date.
204 |
205 | b) The work must carry prominent notices stating that it is
206 | released under this License and any conditions added under section
207 | 7. This requirement modifies the requirement in section 4 to
208 | "keep intact all notices".
209 |
210 | c) You must license the entire work, as a whole, under this
211 | License to anyone who comes into possession of a copy. This
212 | License will therefore apply, along with any applicable section 7
213 | additional terms, to the whole of the work, and all its parts,
214 | regardless of how they are packaged. This License gives no
215 | permission to license the work in any other way, but it does not
216 | invalidate such permission if you have separately received it.
217 |
218 | d) If the work has interactive user interfaces, each must display
219 | Appropriate Legal Notices; however, if the Program has interactive
220 | interfaces that do not display Appropriate Legal Notices, your
221 | work need not make them do so.
222 |
223 | A compilation of a covered work with other separate and independent
224 | works, which are not by their nature extensions of the covered work,
225 | and which are not combined with it such as to form a larger program,
226 | in or on a volume of a storage or distribution medium, is called an
227 | "aggregate" if the compilation and its resulting copyright are not
228 | used to limit the access or legal rights of the compilation's users
229 | beyond what the individual works permit. Inclusion of a covered work
230 | in an aggregate does not cause this License to apply to the other
231 | parts of the aggregate.
232 |
233 | 6. Conveying Non-Source Forms.
234 |
235 | You may convey a covered work in object code form under the terms
236 | of sections 4 and 5, provided that you also convey the
237 | machine-readable Corresponding Source under the terms of this License,
238 | in one of these ways:
239 |
240 | a) Convey the object code in, or embodied in, a physical product
241 | (including a physical distribution medium), accompanied by the
242 | Corresponding Source fixed on a durable physical medium
243 | customarily used for software interchange.
244 |
245 | b) Convey the object code in, or embodied in, a physical product
246 | (including a physical distribution medium), accompanied by a
247 | written offer, valid for at least three years and valid for as
248 | long as you offer spare parts or customer support for that product
249 | model, to give anyone who possesses the object code either (1) a
250 | copy of the Corresponding Source for all the software in the
251 | product that is covered by this License, on a durable physical
252 | medium customarily used for software interchange, for a price no
253 | more than your reasonable cost of physically performing this
254 | conveying of source, or (2) access to copy the
255 | Corresponding Source from a network server at no charge.
256 |
257 | c) Convey individual copies of the object code with a copy of the
258 | written offer to provide the Corresponding Source. This
259 | alternative is allowed only occasionally and noncommercially, and
260 | only if you received the object code with such an offer, in accord
261 | with subsection 6b.
262 |
263 | d) Convey the object code by offering access from a designated
264 | place (gratis or for a charge), and offer equivalent access to the
265 | Corresponding Source in the same way through the same place at no
266 | further charge. You need not require recipients to copy the
267 | Corresponding Source along with the object code. If the place to
268 | copy the object code is a network server, the Corresponding Source
269 | may be on a different server (operated by you or a third party)
270 | that supports equivalent copying facilities, provided you maintain
271 | clear directions next to the object code saying where to find the
272 | Corresponding Source. Regardless of what server hosts the
273 | Corresponding Source, you remain obligated to ensure that it is
274 | available for as long as needed to satisfy these requirements.
275 |
276 | e) Convey the object code using peer-to-peer transmission, provided
277 | you inform other peers where the object code and Corresponding
278 | Source of the work are being offered to the general public at no
279 | charge under subsection 6d.
280 |
281 | A separable portion of the object code, whose source code is excluded
282 | from the Corresponding Source as a System Library, need not be
283 | included in conveying the object code work.
284 |
285 | A "User Product" is either (1) a "consumer product", which means any
286 | tangible personal property which is normally used for personal, family,
287 | or household purposes, or (2) anything designed or sold for incorporation
288 | into a dwelling. In determining whether a product is a consumer product,
289 | doubtful cases shall be resolved in favor of coverage. For a particular
290 | product received by a particular user, "normally used" refers to a
291 | typical or common use of that class of product, regardless of the status
292 | of the particular user or of the way in which the particular user
293 | actually uses, or expects or is expected to use, the product. A product
294 | is a consumer product regardless of whether the product has substantial
295 | commercial, industrial or non-consumer uses, unless such uses represent
296 | the only significant mode of use of the product.
297 |
298 | "Installation Information" for a User Product means any methods,
299 | procedures, authorization keys, or other information required to install
300 | and execute modified versions of a covered work in that User Product from
301 | a modified version of its Corresponding Source. The information must
302 | suffice to ensure that the continued functioning of the modified object
303 | code is in no case prevented or interfered with solely because
304 | modification has been made.
305 |
306 | If you convey an object code work under this section in, or with, or
307 | specifically for use in, a User Product, and the conveying occurs as
308 | part of a transaction in which the right of possession and use of the
309 | User Product is transferred to the recipient in perpetuity or for a
310 | fixed term (regardless of how the transaction is characterized), the
311 | Corresponding Source conveyed under this section must be accompanied
312 | by the Installation Information. But this requirement does not apply
313 | if neither you nor any third party retains the ability to install
314 | modified object code on the User Product (for example, the work has
315 | been installed in ROM).
316 |
317 | The requirement to provide Installation Information does not include a
318 | requirement to continue to provide support service, warranty, or updates
319 | for a work that has been modified or installed by the recipient, or for
320 | the User Product in which it has been modified or installed. Access to a
321 | network may be denied when the modification itself materially and
322 | adversely affects the operation of the network or violates the rules and
323 | protocols for communication across the network.
324 |
325 | Corresponding Source conveyed, and Installation Information provided,
326 | in accord with this section must be in a format that is publicly
327 | documented (and with an implementation available to the public in
328 | source code form), and must require no special password or key for
329 | unpacking, reading or copying.
330 |
331 | 7. Additional Terms.
332 |
333 | "Additional permissions" are terms that supplement the terms of this
334 | License by making exceptions from one or more of its conditions.
335 | Additional permissions that are applicable to the entire Program shall
336 | be treated as though they were included in this License, to the extent
337 | that they are valid under applicable law. If additional permissions
338 | apply only to part of the Program, that part may be used separately
339 | under those permissions, but the entire Program remains governed by
340 | this License without regard to the additional permissions.
341 |
342 | When you convey a copy of a covered work, you may at your option
343 | remove any additional permissions from that copy, or from any part of
344 | it. (Additional permissions may be written to require their own
345 | removal in certain cases when you modify the work.) You may place
346 | additional permissions on material, added by you to a covered work,
347 | for which you have or can give appropriate copyright permission.
348 |
349 | Notwithstanding any other provision of this License, for material you
350 | add to a covered work, you may (if authorized by the copyright holders of
351 | that material) supplement the terms of this License with terms:
352 |
353 | a) Disclaiming warranty or limiting liability differently from the
354 | terms of sections 15 and 16 of this License; or
355 |
356 | b) Requiring preservation of specified reasonable legal notices or
357 | author attributions in that material or in the Appropriate Legal
358 | Notices displayed by works containing it; or
359 |
360 | c) Prohibiting misrepresentation of the origin of that material, or
361 | requiring that modified versions of such material be marked in
362 | reasonable ways as different from the original version; or
363 |
364 | d) Limiting the use for publicity purposes of names of licensors or
365 | authors of the material; or
366 |
367 | e) Declining to grant rights under trademark law for use of some
368 | trade names, trademarks, or service marks; or
369 |
370 | f) Requiring indemnification of licensors and authors of that
371 | material by anyone who conveys the material (or modified versions of
372 | it) with contractual assumptions of liability to the recipient, for
373 | any liability that these contractual assumptions directly impose on
374 | those licensors and authors.
375 |
376 | All other non-permissive additional terms are considered "further
377 | restrictions" within the meaning of section 10. If the Program as you
378 | received it, or any part of it, contains a notice stating that it is
379 | governed by this License along with a term that is a further
380 | restriction, you may remove that term. If a license document contains
381 | a further restriction but permits relicensing or conveying under this
382 | License, you may add to a covered work material governed by the terms
383 | of that license document, provided that the further restriction does
384 | not survive such relicensing or conveying.
385 |
386 | If you add terms to a covered work in accord with this section, you
387 | must place, in the relevant source files, a statement of the
388 | additional terms that apply to those files, or a notice indicating
389 | where to find the applicable terms.
390 |
391 | Additional terms, permissive or non-permissive, may be stated in the
392 | form of a separately written license, or stated as exceptions;
393 | the above requirements apply either way.
394 |
395 | 8. Termination.
396 |
397 | You may not propagate or modify a covered work except as expressly
398 | provided under this License. Any attempt otherwise to propagate or
399 | modify it is void, and will automatically terminate your rights under
400 | this License (including any patent licenses granted under the third
401 | paragraph of section 11).
402 |
403 | However, if you cease all violation of this License, then your
404 | license from a particular copyright holder is reinstated (a)
405 | provisionally, unless and until the copyright holder explicitly and
406 | finally terminates your license, and (b) permanently, if the copyright
407 | holder fails to notify you of the violation by some reasonable means
408 | prior to 60 days after the cessation.
409 |
410 | Moreover, your license from a particular copyright holder is
411 | reinstated permanently if the copyright holder notifies you of the
412 | violation by some reasonable means, this is the first time you have
413 | received notice of violation of this License (for any work) from that
414 | copyright holder, and you cure the violation prior to 30 days after
415 | your receipt of the notice.
416 |
417 | Termination of your rights under this section does not terminate the
418 | licenses of parties who have received copies or rights from you under
419 | this License. If your rights have been terminated and not permanently
420 | reinstated, you do not qualify to receive new licenses for the same
421 | material under section 10.
422 |
423 | 9. Acceptance Not Required for Having Copies.
424 |
425 | You are not required to accept this License in order to receive or
426 | mirai a copy of the Program. Ancillary propagation of a covered work
427 | occurring solely as a consequence of using peer-to-peer transmission
428 | to receive a copy likewise does not require acceptance. However,
429 | nothing other than this License grants you permission to propagate or
430 | modify any covered work. These actions infringe copyright if you do
431 | not accept this License. Therefore, by modifying or propagating a
432 | covered work, you indicate your acceptance of this License to do so.
433 |
434 | 10. Automatic Licensing of Downstream Recipients.
435 |
436 | Each time you convey a covered work, the recipient automatically
437 | receives a license from the original licensors, to mirai, modify and
438 | propagate that work, subject to this License. You are not responsible
439 | for enforcing compliance by third parties with this License.
440 |
441 | An "entity transaction" is a transaction transferring control of an
442 | organization, or substantially all assets of one, or subdividing an
443 | organization, or merging organizations. If propagation of a covered
444 | work results from an entity transaction, each party to that
445 | transaction who receives a copy of the work also receives whatever
446 | licenses to the work the party's predecessor in interest had or could
447 | give under the previous paragraph, plus a right to possession of the
448 | Corresponding Source of the work from the predecessor in interest, if
449 | the predecessor has it or can get it with reasonable efforts.
450 |
451 | You may not impose any further restrictions on the exercise of the
452 | rights granted or affirmed under this License. For example, you may
453 | not impose a license fee, royalty, or other charge for exercise of
454 | rights granted under this License, and you may not initiate litigation
455 | (including a cross-claim or counterclaim in a lawsuit) alleging that
456 | any patent claim is infringed by making, using, selling, offering for
457 | sale, or importing the Program or any portion of it.
458 |
459 | 11. Patents.
460 |
461 | A "contributor" is a copyright holder who authorizes use under this
462 | License of the Program or a work on which the Program is based. The
463 | work thus licensed is called the contributor's "contributor version".
464 |
465 | A contributor's "essential patent claims" are all patent claims
466 | owned or controlled by the contributor, whether already acquired or
467 | hereafter acquired, that would be infringed by some manner, permitted
468 | by this License, of making, using, or selling its contributor version,
469 | but do not include claims that would be infringed only as a
470 | consequence of further modification of the contributor version. For
471 | purposes of this definition, "control" includes the right to grant
472 | patent sublicenses in a manner consistent with the requirements of
473 | this License.
474 |
475 | Each contributor grants you a non-exclusive, worldwide, royalty-free
476 | patent license under the contributor's essential patent claims, to
477 | make, use, sell, offer for sale, import and otherwise mirai, modify and
478 | propagate the contents of its contributor version.
479 |
480 | In the following three paragraphs, a "patent license" is any express
481 | agreement or commitment, however denominated, not to enforce a patent
482 | (such as an express permission to practice a patent or covenant not to
483 | sue for patent infringement). To "grant" such a patent license to a
484 | party means to make such an agreement or commitment not to enforce a
485 | patent against the party.
486 |
487 | If you convey a covered work, knowingly relying on a patent license,
488 | and the Corresponding Source of the work is not available for anyone
489 | to copy, free of charge and under the terms of this License, through a
490 | publicly available network server or other readily accessible means,
491 | then you must either (1) cause the Corresponding Source to be so
492 | available, or (2) arrange to deprive yourself of the benefit of the
493 | patent license for this particular work, or (3) arrange, in a manner
494 | consistent with the requirements of this License, to extend the patent
495 | license to downstream recipients. "Knowingly relying" means you have
496 | actual knowledge that, but for the patent license, your conveying the
497 | covered work in a country, or your recipient's use of the covered work
498 | in a country, would infringe one or more identifiable patents in that
499 | country that you have reason to believe are valid.
500 |
501 | If, pursuant to or in connection with a single transaction or
502 | arrangement, you convey, or propagate by procuring conveyance of, a
503 | covered work, and grant a patent license to some of the parties
504 | receiving the covered work authorizing them to use, propagate, modify
505 | or convey a specific copy of the covered work, then the patent license
506 | you grant is automatically extended to all recipients of the covered
507 | work and works based on it.
508 |
509 | A patent license is "discriminatory" if it does not include within
510 | the scope of its coverage, prohibits the exercise of, or is
511 | conditioned on the non-exercise of one or more of the rights that are
512 | specifically granted under this License. You may not convey a covered
513 | work if you are a party to an arrangement with a third party that is
514 | in the business of distributing software, under which you make payment
515 | to the third party based on the extent of your activity of conveying
516 | the work, and under which the third party grants, to any of the
517 | parties who would receive the covered work from you, a discriminatory
518 | patent license (a) in connection with copies of the covered work
519 | conveyed by you (or copies made from those copies), or (b) primarily
520 | for and in connection with specific products or compilations that
521 | contain the covered work, unless you entered into that arrangement,
522 | or that patent license was granted, prior to 28 March 2007.
523 |
524 | Nothing in this License shall be construed as excluding or limiting
525 | any implied license or other defenses to infringement that may
526 | otherwise be available to you under applicable patent law.
527 |
528 | 12. No Surrender of Others' Freedom.
529 |
530 | If conditions are imposed on you (whether by court order, agreement or
531 | otherwise) that contradict the conditions of this License, they do not
532 | excuse you from the conditions of this License. If you cannot convey a
533 | covered work so as to satisfy simultaneously your obligations under this
534 | License and any other pertinent obligations, then as a consequence you may
535 | not convey it at all. For example, if you agree to terms that obligate you
536 | to collect a royalty for further conveying from those to whom you convey
537 | the Program, the only way you could satisfy both those terms and this
538 | License would be to refrain entirely from conveying the Program.
539 |
540 | 13. Remote Network Interaction; Use with the GNU General Public License.
541 |
542 | Notwithstanding any other provision of this License, if you modify the
543 | Program, your modified version must prominently offer all users
544 | interacting with it remotely through a computer network (if your version
545 | supports such interaction) an opportunity to receive the Corresponding
546 | Source of your version by providing access to the Corresponding Source
547 | from a network server at no charge, through some standard or customary
548 | means of facilitating copying of software. This Corresponding Source
549 | shall include the Corresponding Source for any work covered by version 3
550 | of the GNU General Public License that is incorporated pursuant to the
551 | following paragraph.
552 |
553 | Notwithstanding any other provision of this License, you have
554 | permission to link or combine any covered work with a work licensed
555 | under version 3 of the GNU General Public License into a single
556 | combined work, and to convey the resulting work. The terms of this
557 | License will continue to apply to the part which is the covered work,
558 | but the work with which it is combined will remain governed by version
559 | 3 of the GNU General Public License.
560 |
561 | 14. Revised Versions of this License.
562 |
563 | The Free Software Foundation may publish revised and/or new versions of
564 | the GNU Affero General Public License from time to time. Such new versions
565 | will be similar in spirit to the present version, but may differ in detail to
566 | address new problems or concerns.
567 |
568 | Each version is given a distinguishing version number. If the
569 | Program specifies that a certain numbered version of the GNU Affero General
570 | Public License "or any later version" applies to it, you have the
571 | option of following the terms and conditions either of that numbered
572 | version or of any later version published by the Free Software
573 | Foundation. If the Program does not specify a version number of the
574 | GNU Affero General Public License, you may choose any version ever published
575 | by the Free Software Foundation.
576 |
577 | If the Program specifies that a proxy can decide which future
578 | versions of the GNU Affero General Public License can be used, that proxy's
579 | public statement of acceptance of a version permanently authorizes you
580 | to choose that version for the Program.
581 |
582 | Later license versions may give you additional or different
583 | permissions. However, no additional obligations are imposed on any
584 | author or copyright holder as a result of your choosing to follow a
585 | later version.
586 |
587 | 15. Disclaimer of Warranty.
588 |
589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597 |
598 | 16. Limitation of Liability.
599 |
600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608 | SUCH DAMAGES.
609 |
610 | 17. Interpretation of Sections 15 and 16.
611 |
612 | If the disclaimer of warranty and limitation of liability provided
613 | above cannot be given local legal effect according to their terms,
614 | reviewing courts shall apply local law that most closely approximates
615 | an absolute waiver of all civil liability in connection with the
616 | Program, unless a warranty or assumption of liability accompanies a
617 | copy of the Program in return for a fee.
618 |
619 | END OF TERMS AND CONDITIONS
620 |
621 | How to Apply These Terms to Your New Programs
622 |
623 | If you develop a new program, and you want it to be of the greatest
624 | possible use to the public, the best way to achieve this is to make it
625 | free software which everyone can redistribute and change under these terms.
626 |
627 | To do so, attach the following notices to the program. It is safest
628 | to attach them to the start of each source file to most effectively
629 | state the exclusion of warranty; and each file should have at least
630 | the "copyright" line and a pointer to where the full notice is found.
631 |
632 |
633 | Copyright (C)
634 |
635 | This program is free software: you can redistribute it and/or modify
636 | it under the terms of the GNU Affero General Public License as published
637 | by the Free Software Foundation, either version 3 of the License, or
638 | (at your option) any later version.
639 |
640 | This program is distributed in the hope that it will be useful,
641 | but WITHOUT ANY WARRANTY; without even the implied warranty of
642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643 | GNU Affero General Public License for more details.
644 |
645 | You should have received a copy of the GNU Affero General Public License
646 | along with this program. If not, see .
647 |
648 | Also add information on how to contact you by electronic and paper mail.
649 |
650 | If your software can interact with users remotely through a computer
651 | network, you should also make sure that it provides a way for users to
652 | get its source. For example, if your program is a web application, its
653 | interface could display a "Source" link that leads users to an archive
654 | of the code. There are many ways you could offer source, and different
655 | solutions will be better for different programs; see section 13 for the
656 | specific requirements.
657 |
658 | You should also get your employer (if you work as a programmer) or school,
659 | if any, to sign a "copyright disclaimer" for the program, if necessary.
660 | For more information on this, and how to apply and follow the GNU AGPL, see
661 | .
662 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # [Mirai Skia Plugin](https://github.com/cssxsh/mirai-skia-plugin)
2 |
3 | > Mirai Skia 前置插件
4 |
5 | [](https://search.maven.org/artifact/xyz.cssxsh.mirai/mirai-skia-plugin)
6 | [](https://github.com/cssxsh/mirai-skia-plugin/actions/workflows/test.yml)
7 | [](https://www.codacy.com/gh/cssxsh/mirai-skia-plugin/dashboard?utm_source=github.com&utm_medium=referral&utm_content=cssxsh/mirai-skia-plugin&utm_campaign=Badge_Grade)
8 |
9 | Be based on
10 |
11 | ## SkiaToMirai
12 |
13 | [SkiaToMirai](src/main/kotlin/xyz/cssxsh/mirai/skia/SkiaToMirai.kt)
14 | [SkiaExternalResource](src/main/kotlin/xyz/cssxsh/mirai/skia/SkiaExternalResource.kt)
15 |
16 | ## Example
17 |
18 | [Example](src/main/kotlin/xyz/cssxsh/skia/Example.kt)
19 |
20 | ## Dependency
21 |
22 | 作为 Mirai Console 前置插件:
23 | 配置文件 `build.gradle.kts`
24 | ```kotlin
25 | repositories {
26 | mavenCentral()
27 | // skiko 还未发布正式版到 Central,需要加入下面的 repo
28 | maven(url = "https://maven.pkg.jetbrains.space/public/p/compose/dev")
29 | }
30 |
31 | dependencies {
32 | compileOnly("xyz.cssxsh.mirai:mirai-skia-plugin:${version}")
33 | }
34 |
35 | mirai {
36 | jvmTarget = JavaVersion.VERSION_11
37 | }
38 | ```
39 | 定义 `dependsOn`
40 | ```kotlin
41 | object MemeHelperPlugin : KotlinPlugin(
42 | JvmPluginDescription(
43 | id = "xyz.cssxsh.mirai.plugin.meme-helper",
44 | name = "meme-helper",
45 | version = "1.0.2",
46 | ) {
47 | author("cssxsh")
48 | dependsOn("xyz.cssxsh.mirai.plugin.mirai-skia-plugin", ">= 1.1.0", false)
49 | }
50 | )
51 | ```
52 |
53 | 作为 Mirai Core Jvm 引用:
54 | 配置文件 `build.gradle.kts`
55 | ```kotlin
56 | repositories {
57 | mavenCentral()
58 | }
59 |
60 | dependencies {
61 | implementation("xyz.cssxsh.mirai:mirai-skia-plugin:${version}")
62 | }
63 | ```
64 | 手动调用库加载函数
65 | ```kotlin
66 | import xyz.cssxsh.mirai.skia.*
67 |
68 | checkPlatform()
69 | loadJNILibrary()
70 | ```
71 |
72 | ## GIF
73 |
74 | 由于 Skiko 没有携带 GIF 编码器,
75 | 这里提供两个实现
76 | * [kotlin](src/main/kotlin/xyz/cssxsh/skia/gif) - [petpet](src/main/kotlin/xyz/cssxsh/skia/Example.kt)
77 | * [rust](src/main/kotlin/xyz/cssxsh/gif) (Base on [JNI](https://github.com/cssxsh/gif-jni)) - [dear](src/main/kotlin/xyz/cssxsh/skia/Example.kt)
78 |
79 | ## 安装
80 |
81 | ### MCL 指令安装
82 |
83 | **请确认 mcl.jar 的版本是 2.1.0+**
84 | `./mcl --update-package xyz.cssxsh.mirai:mirai-skia-plugin --channel maven-stable --type plugins`
85 |
86 | ### 手动安装
87 |
88 | 1. 从 [Releases](https://github.com/cssxsh/mirai-skia-plugin/releases) 或者 [Maven](https://repo1.maven.org/maven2/xyz/cssxsh/mirai/mirai-skia-plugin/) 下载 `mirai2.jar`
89 | 2. 将其放入 `plugins` 文件夹中
90 |
91 | ### 缺少库
92 |
93 | 如果启动后出现 `XXX: cannot open shared object file: No such file or directory` 或者 `XXX: 无法打开共享对象文件: 没有那个文件或目录`
94 | 说明你的 `Linux` 系统缺少了某些前置库文件 `XXX`, 你需要自行补充安装, 可以通过 检索相关信息
95 |
96 | 例如,出现 `libGL.so.1: cannot open shared object file: No such file or directory`
97 | 参阅 , 找到对应的系统及版本然后,进入相关库介绍页面,下拉找到安装指令
98 |
99 | ## 兼容性
100 |
101 | | OS/Arch | Plugin | Skiko | Gif |
102 | |:----------------------:|:------:|:------:|:-----:|
103 | | Windows-10-X64 | 1.3.2 | 0.7.58 | 2.0.8 |
104 | | GNU/Linux-X64 | 1.3.2 | 0.7.58 | 2.0.8 |
105 | | GNU/Linux-ARM64 | 1.3.2 | 0.7.58 | 2.0.8 |
106 | | MacOS-X64 | 1.3.2 | 0.7.58 | 2.0.8 |
107 | | MacOS-ARM64 | 1.3.2 | 0.7.58 | 2.0.8 |
108 | | Termux (Android-ARM64) | 1.3.2 | 0.7.54 | 2.0.8 |
109 |
110 | 暂时不支持 `Alpine Linux` 等 `MUSL/linux` 系统, 你可以关注 [](https://github.com/cssxsh/mirai-skia-plugin/issues/11)
111 |
112 | ## [爱发电](https://afdian.net/@cssxsh)
113 |
114 | 
--------------------------------------------------------------------------------
/build.gradle.kts:
--------------------------------------------------------------------------------
1 | plugins {
2 | kotlin("jvm") version "1.8.22"
3 | kotlin("plugin.serialization") version "1.8.22"
4 |
5 | id("net.mamoe.mirai-console") version "2.16.0"
6 | id("me.him188.maven-central-publish") version "1.0.0"
7 | }
8 |
9 | group = "xyz.cssxsh.mirai"
10 | version = "1.3.2"
11 |
12 | mavenCentralPublish {
13 | useCentralS01()
14 | singleDevGithubProject("cssxsh", "mirai-skia-plugin")
15 | licenseFromGitHubProject("AGPL-3.0")
16 | workingDir = System.getenv("PUBLICATION_TEMP")?.let { file(it).resolve(projectName) }
17 | ?: buildDir.resolve("publishing-tmp")
18 | publication {
19 | artifact(tasks["buildPlugin"])
20 | }
21 | }
22 |
23 | repositories {
24 | mavenCentral()
25 | maven(url = "https://maven.pkg.jetbrains.space/public/p/compose/dev")
26 | }
27 |
28 | dependencies {
29 | api("org.jetbrains.skiko:skiko-awt:0.7.97")
30 | implementation("org.apache.commons:commons-compress:1.26.1")
31 | implementation("org.tukaani:xz:1.9")
32 | implementation("org.jsoup:jsoup:1.17.2")
33 | testImplementation(kotlin("test"))
34 | //
35 | implementation(platform("net.mamoe:mirai-bom:2.16.0"))
36 | compileOnly("net.mamoe:mirai-core-utils")
37 | compileOnly("net.mamoe:mirai-console-compiler-common")
38 | testImplementation("net.mamoe:mirai-logging-slf4j")
39 | //
40 | implementation(platform("io.ktor:ktor-bom:2.3.10"))
41 | implementation("io.ktor:ktor-client-okhttp")
42 | implementation("io.ktor:ktor-client-encoding")
43 | //
44 | implementation(platform("com.squareup.okhttp3:okhttp-bom:4.12.0"))
45 | implementation("com.squareup.okhttp3:okhttp-dnsoverhttps")
46 | //
47 | implementation(platform("org.slf4j:slf4j-parent:2.0.13"))
48 | testImplementation("org.slf4j:slf4j-simple")
49 | }
50 |
51 | kotlin {
52 | explicitApi()
53 | }
54 |
55 | mirai {
56 | jvmTarget = JavaVersion.VERSION_11
57 | }
58 |
59 | tasks {
60 | test {
61 | useJUnitPlatform()
62 | }
63 | }
64 |
65 |
--------------------------------------------------------------------------------
/example/90446978_p0.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cssxsh/mirai-skia-plugin/0a36163cc6d3dcf667365eabd27b9b17d0dc67a7/example/90446978_p0.png
--------------------------------------------------------------------------------
/example/90487779_p0.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cssxsh/mirai-skia-plugin/0a36163cc6d3dcf667365eabd27b9b17d0dc67a7/example/90487779_p0.png
--------------------------------------------------------------------------------
/example/Osu.svg:
--------------------------------------------------------------------------------
1 |
75 |
--------------------------------------------------------------------------------
/example/cssxsh.svg:
--------------------------------------------------------------------------------
1 |
195 |
--------------------------------------------------------------------------------
/example/dear.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cssxsh/mirai-skia-plugin/0a36163cc6d3dcf667365eabd27b9b17d0dc67a7/example/dear.gif
--------------------------------------------------------------------------------
/example/face.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cssxsh/mirai-skia-plugin/0a36163cc6d3dcf667365eabd27b9b17d0dc67a7/example/face.png
--------------------------------------------------------------------------------
/example/osu-logo-triangles.svg:
--------------------------------------------------------------------------------
1 |
2 |
3 |
5 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 |
107 |
--------------------------------------------------------------------------------
/example/osu-logo-white.svg:
--------------------------------------------------------------------------------
1 |
2 |
3 |
5 |
8 |
27 |
30 |
31 |
--------------------------------------------------------------------------------
/example/sprite.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cssxsh/mirai-skia-plugin/0a36163cc6d3dcf667365eabd27b9b17d0dc67a7/example/sprite.png
--------------------------------------------------------------------------------
/example/style.test.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cssxsh/mirai-skia-plugin/0a36163cc6d3dcf667365eabd27b9b17d0dc67a7/example/style.test.jpg
--------------------------------------------------------------------------------
/example/zzkia.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cssxsh/mirai-skia-plugin/0a36163cc6d3dcf667365eabd27b9b17d0dc67a7/example/zzkia.jpg
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | kotlin.code.style=official
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cssxsh/mirai-skia-plugin/0a36163cc6d3dcf667365eabd27b9b17d0dc67a7/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionBase=GRADLE_USER_HOME
2 | distributionPath=wrapper/dists
3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.4-all.zip
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | #
4 | # Copyright 2015 the original author or authors.
5 | #
6 | # Licensed under the Apache License, Version 2.0 (the "License");
7 | # you may not use this file except in compliance with the License.
8 | # You may obtain a copy of the License at
9 | #
10 | # https://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | # See the License for the specific language governing permissions and
16 | # limitations under the License.
17 | #
18 |
19 | ##############################################################################
20 | ##
21 | ## Gradle start up script for UN*X
22 | ##
23 | ##############################################################################
24 |
25 | # Attempt to set APP_HOME
26 | # Resolve links: $0 may be a link
27 | PRG="$0"
28 | # Need this for relative symlinks.
29 | while [ -h "$PRG" ] ; do
30 | ls=`ls -ld "$PRG"`
31 | link=`expr "$ls" : '.*-> \(.*\)$'`
32 | if expr "$link" : '/.*' > /dev/null; then
33 | PRG="$link"
34 | else
35 | PRG=`dirname "$PRG"`"/$link"
36 | fi
37 | done
38 | SAVED="`pwd`"
39 | cd "`dirname \"$PRG\"`/" >/dev/null
40 | APP_HOME="`pwd -P`"
41 | cd "$SAVED" >/dev/null
42 |
43 | APP_NAME="Gradle"
44 | APP_BASE_NAME=`basename "$0"`
45 |
46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
48 |
49 | # Use the maximum available, or set MAX_FD != -1 to use that value.
50 | MAX_FD="maximum"
51 |
52 | warn () {
53 | echo "$*"
54 | }
55 |
56 | die () {
57 | echo
58 | echo "$*"
59 | echo
60 | exit 1
61 | }
62 |
63 | # OS specific support (must be 'true' or 'false').
64 | cygwin=false
65 | msys=false
66 | darwin=false
67 | nonstop=false
68 | case "`uname`" in
69 | CYGWIN* )
70 | cygwin=true
71 | ;;
72 | Darwin* )
73 | darwin=true
74 | ;;
75 | MSYS* | MINGW* )
76 | msys=true
77 | ;;
78 | NONSTOP* )
79 | nonstop=true
80 | ;;
81 | esac
82 |
83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
84 |
85 |
86 | # Determine the Java command to use to start the JVM.
87 | if [ -n "$JAVA_HOME" ] ; then
88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
89 | # IBM's JDK on AIX uses strange locations for the executables
90 | JAVACMD="$JAVA_HOME/jre/sh/java"
91 | else
92 | JAVACMD="$JAVA_HOME/bin/java"
93 | fi
94 | if [ ! -x "$JAVACMD" ] ; then
95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
96 |
97 | Please set the JAVA_HOME variable in your environment to match the
98 | location of your Java installation."
99 | fi
100 | else
101 | JAVACMD="java"
102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
103 |
104 | Please set the JAVA_HOME variable in your environment to match the
105 | location of your Java installation."
106 | fi
107 |
108 | # Increase the maximum file descriptors if we can.
109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
110 | MAX_FD_LIMIT=`ulimit -H -n`
111 | if [ $? -eq 0 ] ; then
112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
113 | MAX_FD="$MAX_FD_LIMIT"
114 | fi
115 | ulimit -n $MAX_FD
116 | if [ $? -ne 0 ] ; then
117 | warn "Could not set maximum file descriptor limit: $MAX_FD"
118 | fi
119 | else
120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
121 | fi
122 | fi
123 |
124 | # For Darwin, add options to specify how the application appears in the dock
125 | if $darwin; then
126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
127 | fi
128 |
129 | # For Cygwin or MSYS, switch paths to Windows format before running java
130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
133 |
134 | JAVACMD=`cygpath --unix "$JAVACMD"`
135 |
136 | # We build the pattern for arguments to be converted via cygpath
137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
138 | SEP=""
139 | for dir in $ROOTDIRSRAW ; do
140 | ROOTDIRS="$ROOTDIRS$SEP$dir"
141 | SEP="|"
142 | done
143 | OURCYGPATTERN="(^($ROOTDIRS))"
144 | # Add a user-defined pattern to the cygpath arguments
145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
147 | fi
148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
149 | i=0
150 | for arg in "$@" ; do
151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
153 |
154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
156 | else
157 | eval `echo args$i`="\"$arg\""
158 | fi
159 | i=`expr $i + 1`
160 | done
161 | case $i in
162 | 0) set -- ;;
163 | 1) set -- "$args0" ;;
164 | 2) set -- "$args0" "$args1" ;;
165 | 3) set -- "$args0" "$args1" "$args2" ;;
166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;;
167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
172 | esac
173 | fi
174 |
175 | # Escape application args
176 | save () {
177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
178 | echo " "
179 | }
180 | APP_ARGS=`save "$@"`
181 |
182 | # Collect all arguments for the java command, following the shell quoting and substitution rules
183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
184 |
185 | exec "$JAVACMD" "$@"
186 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @rem
2 | @rem Copyright 2015 the original author or authors.
3 | @rem
4 | @rem Licensed under the Apache License, Version 2.0 (the "License");
5 | @rem you may not use this file except in compliance with the License.
6 | @rem You may obtain a copy of the License at
7 | @rem
8 | @rem https://www.apache.org/licenses/LICENSE-2.0
9 | @rem
10 | @rem Unless required by applicable law or agreed to in writing, software
11 | @rem distributed under the License is distributed on an "AS IS" BASIS,
12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | @rem See the License for the specific language governing permissions and
14 | @rem limitations under the License.
15 | @rem
16 |
17 | @if "%DEBUG%" == "" @echo off
18 | @rem ##########################################################################
19 | @rem
20 | @rem Gradle startup script for Windows
21 | @rem
22 | @rem ##########################################################################
23 |
24 | @rem Set local scope for the variables with windows NT shell
25 | if "%OS%"=="Windows_NT" setlocal
26 |
27 | set DIRNAME=%~dp0
28 | if "%DIRNAME%" == "" set DIRNAME=.
29 | set APP_BASE_NAME=%~n0
30 | set APP_HOME=%DIRNAME%
31 |
32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter.
33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
34 |
35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
37 |
38 | @rem Find java.exe
39 | if defined JAVA_HOME goto findJavaFromJavaHome
40 |
41 | set JAVA_EXE=java.exe
42 | %JAVA_EXE% -version >NUL 2>&1
43 | if "%ERRORLEVEL%" == "0" goto execute
44 |
45 | echo.
46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
47 | echo.
48 | echo Please set the JAVA_HOME variable in your environment to match the
49 | echo location of your Java installation.
50 |
51 | goto fail
52 |
53 | :findJavaFromJavaHome
54 | set JAVA_HOME=%JAVA_HOME:"=%
55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
56 |
57 | if exist "%JAVA_EXE%" goto execute
58 |
59 | echo.
60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
61 | echo.
62 | echo Please set the JAVA_HOME variable in your environment to match the
63 | echo location of your Java installation.
64 |
65 | goto fail
66 |
67 | :execute
68 | @rem Setup the command line
69 |
70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
71 |
72 |
73 | @rem Execute Gradle
74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
75 |
76 | :end
77 | @rem End local scope for the variables with windows NT shell
78 | if "%ERRORLEVEL%"=="0" goto mainEnd
79 |
80 | :fail
81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
82 | rem the _cmd.exe /c_ return code!
83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
84 | exit /b 1
85 |
86 | :mainEnd
87 | if "%OS%"=="Windows_NT" endlocal
88 |
89 | :omega
90 |
--------------------------------------------------------------------------------
/settings.gradle.kts:
--------------------------------------------------------------------------------
1 | rootProject.name = "mirai-skia-plugin"
--------------------------------------------------------------------------------
/src/main/kotlin/xyz/cssxsh/gif/Ditherer.kt:
--------------------------------------------------------------------------------
1 | package xyz.cssxsh.gif
2 |
3 | import org.jetbrains.skia.*
4 | import org.jetbrains.skia.impl.*
5 |
6 | /**
7 | * 抖动器
8 | */
9 | @Suppress("INVISIBLE_REFERENCE", "INVISIBLE_MEMBER")
10 | public interface Ditherer {
11 |
12 | /**
13 | * 抖动处理
14 | * @param bitmap 原图
15 | * @param palette 色板
16 | * @return 处理完成的数据
17 | */
18 | public fun handle(bitmap: Bitmap, palette: Data): Data
19 |
20 | /**
21 | * Atkinson 算法
22 | */
23 | public object Atkinson : Ditherer {
24 | private external fun native(bitmap: NativePointer, palette: NativePointer): NativePointer
25 |
26 | override fun handle(bitmap: Bitmap, palette: Data): Data {
27 | return Data(ptr = native(bitmap._ptr, palette._ptr))
28 | }
29 | }
30 |
31 | /**
32 | * JJN 算法
33 | */
34 | public object JJN : Ditherer {
35 | private external fun native(bitmap: NativePointer, palette: NativePointer): NativePointer
36 |
37 | override fun handle(bitmap: Bitmap, palette: Data): Data {
38 | return Data(ptr = native(bitmap._ptr, palette._ptr))
39 | }
40 | }
41 |
42 | /**
43 | * SierraLite 算法
44 | */
45 | public object SierraLite : Ditherer {
46 | private external fun native(bitmap: NativePointer, palette: NativePointer): NativePointer
47 |
48 | override fun handle(bitmap: Bitmap, palette: Data): Data {
49 | return Data(ptr = native(bitmap._ptr, palette._ptr))
50 | }
51 | }
52 |
53 | /**
54 | * Stucki 算法
55 | */
56 | public object Stucki : Ditherer {
57 | private external fun native(bitmap: NativePointer, palette: NativePointer): NativePointer
58 |
59 | override fun handle(bitmap: Bitmap, palette: Data): Data {
60 | return Data(ptr = native(bitmap._ptr, palette._ptr))
61 | }
62 | }
63 |
64 | public companion object {
65 | init {
66 | Library.staticLoad()
67 | }
68 | }
69 | }
--------------------------------------------------------------------------------
/src/main/kotlin/xyz/cssxsh/gif/Encoder.kt:
--------------------------------------------------------------------------------
1 | package xyz.cssxsh.gif
2 |
3 | import org.jetbrains.skia.*
4 | import org.jetbrains.skia.impl.*
5 | import java.io.*
6 |
7 | /**
8 | * 编码器最终要调用 [close] 完成对文件尾的处理
9 | */
10 | @Suppress("INVISIBLE_REFERENCE", "INVISIBLE_MEMBER")
11 | public class Encoder internal constructor(ptr: NativePointer) : Native(ptr), Closeable {
12 | public constructor(path: String, width: Int, height: Int, palette: Data = Data.makeEmpty()) :
13 | this(ptr = file(path, width, height, palette._ptr))
14 |
15 | public constructor(file: File, width: Int, height: Int, palette: Data = Data.makeEmpty()) :
16 | this(ptr = file(file.path, width, height, palette._ptr))
17 |
18 | public var repeat: Int = 0
19 | set(value) {
20 | setRepeat(_ptr, value)
21 | field = value
22 | }
23 |
24 | /**
25 | * 写入帧
26 | * @param frame 帧
27 | */
28 | public fun writeFrame(frame: Frame) {
29 | writeFrame(_ptr, frame._ptr)
30 | }
31 |
32 | /**
33 | * 写入图片作为帧
34 | * @param image 图片
35 | * @param mills 延时
36 | * @param disposal 切换模式
37 | */
38 | public fun writeImage(image: Image, mills: Int, disposal: AnimationDisposalMode, speed: Int = 1) {
39 | writeImage(_ptr, image._ptr, mills / 10, disposal.ordinal, speed)
40 | }
41 |
42 | /**
43 | * 写入位图作为帧
44 | * @param bitmap 位图
45 | * @param mills 延时
46 | * @param disposal 切换模式
47 | */
48 | public fun writeBitmap(bitmap: Bitmap, mills: Int, disposal: AnimationDisposalMode, speed: Int = 1) {
49 | writeBitmap(_ptr, bitmap._ptr, mills / 10, disposal.ordinal, speed)
50 | }
51 |
52 | /**
53 | * 关闭,并输出内容到文件
54 | */
55 | public override fun close() {
56 | close(_ptr)
57 | }
58 |
59 | private companion object {
60 | init {
61 | Library.staticLoad()
62 | }
63 |
64 | @JvmStatic
65 | external fun file(path: String, width: Int, height: Int, palette: NativePointer): NativePointer
66 |
67 | @JvmStatic
68 | external fun setRepeat(self: NativePointer, value: Int)
69 |
70 | @JvmStatic
71 | external fun writeFrame(self: NativePointer, frame: NativePointer)
72 |
73 | @JvmStatic
74 | external fun writeImage(self: NativePointer, image: NativePointer, centi: Int, dispose: Int, speed: Int)
75 |
76 | @JvmStatic
77 | external fun writeBitmap(self: NativePointer, bitmap: NativePointer, centi: Int, dispose: Int, speed: Int)
78 |
79 | @JvmStatic
80 | external fun close(self: NativePointer)
81 | }
82 | }
--------------------------------------------------------------------------------
/src/main/kotlin/xyz/cssxsh/gif/Frame.kt:
--------------------------------------------------------------------------------
1 | package xyz.cssxsh.gif
2 |
3 | import org.jetbrains.skia.*
4 | import org.jetbrains.skia.impl.*
5 | import java.io.*
6 |
7 | /**
8 | * GIF帧
9 | */
10 | @Suppress("INVISIBLE_MEMBER")
11 | public class Frame internal constructor(ptr: NativePointer) : Native(ptr), Closeable {
12 | public constructor() : this(ptr = default())
13 |
14 | public var delay: Int
15 | get() = getDelay(self = _ptr) * 10
16 | set(value) = setDelay(self = _ptr, value = value / 10)
17 |
18 | public var dispose: AnimationDisposalMode
19 | get() = AnimationDisposalMode.values()[getDispose(self = _ptr)]
20 | set(value) = setDispose(self = _ptr, value = value.ordinal)
21 |
22 | public var rect: IRect
23 | get() = getRect(self = _ptr).let { (top, left, width, height) -> IRect.makeXYWH(top, left, width, height) }
24 | set(value) = setRect(self = _ptr, value.top, value.left, value.width, value.height)
25 |
26 | public val palette: Data
27 | get() = Data(ptr = getPalette(self = _ptr))
28 |
29 | override fun close() {
30 | close(ptr = _ptr)
31 | }
32 |
33 | public companion object {
34 | init {
35 | Library.staticLoad()
36 | }
37 |
38 | /**
39 | * 从 GIF 像素创建帧
40 | * @param width 宽
41 | * @param height 高
42 | * @param pixels 像素数据
43 | * @param transparent 透明像素Index
44 | */
45 | public fun fromIndexedPixels(width: Int, height: Int, pixels: Data, transparent: Int?): Frame {
46 | return Frame(ptr = fromIndexedPixels(width, height, pixels._ptr, transparent ?: -1))
47 | }
48 |
49 | /**
50 | * 从 GIF 像素创建帧
51 | * @param width 宽
52 | * @param height 高
53 | * @param pixels 像素数据
54 | * @param palette 颜色盘
55 | * @param transparent 透明像素Index
56 | */
57 | public fun fromPalettePixels(width: Int, height: Int, pixels: Data, palette: Data, transparent: Int?): Frame {
58 | return Frame(ptr = fromPalettePixels(width, height, pixels._ptr, palette._ptr, transparent ?: -1))
59 | }
60 |
61 | /**
62 | * 从 RGB 像素创建帧
63 | * @param pixels 像素数据
64 | * @param width 宽
65 | * @param height 高
66 | */
67 | public fun fromRGBSpeed(pixels: Data, width: Int, height: Int, speed: Int = 0): Frame {
68 | return Frame(ptr = fromRGBSpeed(width, height, pixels._ptr, speed))
69 | }
70 |
71 | /**
72 | * 从 RGBA 像素创建帧
73 | * @param pixels 像素数据
74 | * @param width 宽
75 | * @param height 高
76 | */
77 | public fun fromRGBASpeed(pixels: Data, width: Int, height: Int, speed: Int = 0): Frame {
78 | return Frame(ptr = fromRGBASpeed(width, height, pixels._ptr, speed))
79 | }
80 |
81 | /**
82 | * 从图片创建帧
83 | * @param image 图片
84 | */
85 | public fun fromImage(image: Image, speed: Int = 1): Frame {
86 | return Frame(ptr = fromImage(image._ptr, speed))
87 | }
88 |
89 | /**
90 | * 从位图创建帧
91 | * @param bitmap 位图
92 | */
93 | public fun fromBitmap(bitmap: Bitmap, speed: Int = 1): Frame {
94 | return Frame(ptr = fromBitmap(bitmap._ptr, speed))
95 | }
96 |
97 | /**
98 | * 从像素图创建帧
99 | * @param pixmap 像素图
100 | */
101 | public fun fromPixmap(pixmap: Pixmap, speed: Int = 1): Frame {
102 | return Frame(ptr = fromPixmap(pixmap._ptr, speed))
103 | }
104 |
105 | @JvmStatic
106 | internal external fun default(): NativePointer
107 |
108 | @JvmStatic
109 | internal external fun fromIndexedPixels(
110 | width: Int,
111 | height: Int,
112 | pixels: NativePointer,
113 | transparent: Int
114 | ): NativePointer
115 |
116 | @JvmStatic
117 | internal external fun fromPalettePixels(
118 | width: Int,
119 | height: Int,
120 | pixels: NativePointer,
121 | palette: NativePointer,
122 | transparent: Int
123 | ): NativePointer
124 |
125 | @JvmStatic
126 | internal external fun fromRGBSpeed(width: Int, height: Int, bytes: NativePointer, speed: Int): NativePointer
127 |
128 | @JvmStatic
129 | internal external fun fromRGBASpeed(width: Int, height: Int, bytes: NativePointer, speed: Int): NativePointer
130 |
131 | @JvmStatic
132 | internal external fun fromImage(image: NativePointer, speed: Int): NativePointer
133 |
134 | @JvmStatic
135 | internal external fun fromBitmap(bitmap: NativePointer, speed: Int): NativePointer
136 |
137 | @JvmStatic
138 | internal external fun fromPixmap(pixmap: NativePointer, speed: Int): NativePointer
139 |
140 | @JvmStatic
141 | internal external fun close(ptr: NativePointer): NativePointer
142 |
143 | @JvmStatic
144 | internal external fun getDelay(self: NativePointer): Int
145 |
146 | @JvmStatic
147 | internal external fun setDelay(self: NativePointer, value: Int)
148 |
149 | @JvmStatic
150 | internal external fun getDispose(self: NativePointer): Int
151 |
152 | @JvmStatic
153 | internal external fun setDispose(self: NativePointer, value: Int)
154 |
155 | @JvmStatic
156 | internal external fun getRect(self: NativePointer): IntArray
157 |
158 | @JvmStatic
159 | internal external fun setRect(self: NativePointer, top: Int, left: Int, width: Int, height: Int)
160 |
161 | @JvmStatic
162 | internal external fun getPalette(self: NativePointer): NativePointer
163 | }
164 | }
165 |
--------------------------------------------------------------------------------
/src/main/kotlin/xyz/cssxsh/gif/Library.kt:
--------------------------------------------------------------------------------
1 | package xyz.cssxsh.gif
2 |
3 | import org.jetbrains.skiko.*
4 | import java.io.*
5 | import java.nio.file.*
6 | import java.util.concurrent.atomic.*
7 |
8 | /**
9 | * GIF JNI 加载器
10 | * @see org.jetbrains.skiko.Library
11 | */
12 | public object Library {
13 | @PublishedApi
14 | internal const val GIF_LIBRARY_PATH_PROPERTY: String = "gif.library.path"
15 | @PublishedApi
16 | internal val cacheRoot: String = "${System.getProperty("user.home")}/.gif/"
17 | private val libraryPath = System.getProperty(GIF_LIBRARY_PATH_PROPERTY)
18 | private var copyDir: File? = null
19 | @PublishedApi
20 | internal var loaded: AtomicBoolean = AtomicBoolean(false)
21 |
22 | /**
23 | * 尝试加载 GIF_LIBRARY
24 | */
25 | public fun staticLoad() {
26 | if (loaded.compareAndSet(false, true)) {
27 | load()
28 | }
29 | }
30 |
31 | private fun loadLibraryOrCopy(library: File) {
32 | try {
33 | System.load(library.absolutePath)
34 | } catch (e: UnsatisfiedLinkError) {
35 | if (e.message?.contains("already loaded in another classloader") == true) {
36 | copyDir = Files.createTempDirectory("gif").toFile()
37 | val tempFile = copyDir!!.resolve(library.name)
38 | Files.copy(library.toPath(), tempFile.toPath(), StandardCopyOption.REPLACE_EXISTING)
39 | tempFile.deleteOnExit()
40 | System.load(tempFile.absolutePath)
41 | } else {
42 | throw e
43 | }
44 | }
45 | }
46 |
47 | private fun unpackIfNeeded(dest: File, resourceName: String): File {
48 | val file = File(dest, resourceName)
49 | if (!file.exists()) {
50 | val tempFile = File.createTempFile("gif", "", dest)
51 | Library::class.java.getResourceAsStream("/$resourceName")!!.use { input ->
52 | Files.copy(input, tempFile.toPath(), StandardCopyOption.REPLACE_EXISTING)
53 | }
54 | Files.move(tempFile.toPath(), file.toPath(), StandardCopyOption.ATOMIC_MOVE)
55 | }
56 | return file
57 | }
58 |
59 | @Synchronized
60 | internal fun load() {
61 | val name = "gif-$hostId"
62 | val platformName = System.mapLibraryName(name)
63 |
64 | if (hostOs == OS.Android) {
65 | System.loadLibrary("gif-$hostId")
66 | return
67 | }
68 |
69 | // First try: system property is set.
70 | if (libraryPath != null) {
71 | val library = File(libraryPath, platformName)
72 | loadLibraryOrCopy(library)
73 | return
74 | }
75 |
76 | val jvmFiles = File(System.getProperty("java.home"), if (hostOs.isWindows) "bin" else "lib")
77 | val pathInJvm = jvmFiles.resolve(platformName)
78 | if (pathInJvm.exists()) {
79 | loadLibraryOrCopy(pathInJvm)
80 | return
81 | }
82 |
83 | val hashResourceStream = Library::class.java.getResourceAsStream(
84 | "/$platformName.sha256"
85 | ) ?: throw LibraryLoadException(
86 | "Cannot find $platformName.sha256, proper native dependency missing."
87 | )
88 | val hash = hashResourceStream.use { it.bufferedReader().readLine() }
89 |
90 | val cacheDir = File(cacheRoot, hash)
91 | cacheDir.mkdirs()
92 | val library = unpackIfNeeded(cacheDir, platformName)
93 | loadLibraryOrCopy(library)
94 | }
95 | }
--------------------------------------------------------------------------------
/src/main/kotlin/xyz/cssxsh/gif/Quantizer.kt:
--------------------------------------------------------------------------------
1 | package xyz.cssxsh.gif
2 |
3 | import org.jetbrains.skia.*
4 | import org.jetbrains.skia.impl.*
5 |
6 | /**
7 | * 量化器
8 | * @see OctTree
9 | * @see MedianCut
10 | * @see KMeans
11 | */
12 | @Suppress("INVISIBLE_REFERENCE", "INVISIBLE_MEMBER")
13 | public interface Quantizer {
14 |
15 | /**
16 | * 量化处理
17 | * @param bitmap 原图
18 | * @param maxColorCount 最大颜色数
19 | * @param sort 排序
20 | * @return GIF位图数据
21 | */
22 | public fun handle(bitmap: Bitmap, maxColorCount: Int = 256, sort: Boolean = false): Data
23 |
24 | /**
25 | * 八叉树量化器
26 | */
27 | public object OctTree : Quantizer {
28 | private external fun native(bitmap: NativePointer, maxColorCount: Int, sort: Boolean): NativePointer
29 |
30 | override fun handle(bitmap: Bitmap, maxColorCount: Int, sort: Boolean): Data {
31 | val p = native(bitmap._ptr, maxColorCount, sort)
32 | return Data(ptr = p)
33 | }
34 | }
35 |
36 | /**
37 | * 中值量化器
38 | */
39 | public object MedianCut : Quantizer {
40 | private external fun native(bitmap: NativePointer, maxColorCount: Int, sort: Boolean): NativePointer
41 |
42 | override fun handle(bitmap: Bitmap, maxColorCount: Int, sort: Boolean): Data {
43 | return Data(ptr = native(bitmap._ptr, maxColorCount, sort))
44 | }
45 | }
46 |
47 |
48 | /**
49 | * KMeans 量化器
50 | */
51 | public object KMeans : Quantizer {
52 | private external fun native(bitmap: NativePointer, maxColorCount: Int, sort: Boolean): NativePointer
53 |
54 | override fun handle(bitmap: Bitmap, maxColorCount: Int, sort: Boolean): Data {
55 | return Data(ptr = native(bitmap._ptr, maxColorCount, sort))
56 | }
57 | }
58 |
59 | public companion object {
60 | init {
61 | Library.staticLoad()
62 | }
63 | }
64 | }
--------------------------------------------------------------------------------
/src/main/kotlin/xyz/cssxsh/gif/Version.kt:
--------------------------------------------------------------------------------
1 | package xyz.cssxsh.gif
2 |
3 | /**
4 | * GIF JNI 版本信息
5 | */
6 | public object Version {
7 | public const val gif: String = "2.0.8"
8 | }
--------------------------------------------------------------------------------
/src/main/kotlin/xyz/cssxsh/mirai/skia/MiraiSkiaDownloader.kt:
--------------------------------------------------------------------------------
1 | package xyz.cssxsh.mirai.skia
2 |
3 | import io.ktor.client.*
4 | import io.ktor.client.content.*
5 | import io.ktor.client.engine.okhttp.*
6 | import io.ktor.client.plugins.*
7 | import io.ktor.client.plugins.compression.*
8 | import io.ktor.client.request.*
9 | import io.ktor.client.statement.*
10 | import io.ktor.http.*
11 | import io.ktor.utils.io.jvm.javaio.*
12 | import kotlinx.coroutines.*
13 | import net.mamoe.mirai.utils.*
14 | import okhttp3.Dns
15 | import okhttp3.HttpUrl.Companion.toHttpUrl
16 | import okhttp3.dnsoverhttps.DnsOverHttps
17 | import org.apache.commons.compress.archivers.sevenz.*
18 | import org.apache.commons.compress.archivers.tar.*
19 | import org.apache.commons.compress.compressors.gzip.*
20 | import org.jetbrains.skiko.*
21 | import xyz.cssxsh.skia.*
22 | import java.io.*
23 | import java.nio.file.*
24 | import java.util.jar.*
25 | import java.util.zip.*
26 |
27 | internal val logger by lazy {
28 | try {
29 | MiraiSkiaPlugin.logger
30 | } catch (_: ExceptionInInitializerError) {
31 | MiraiLogger.Factory.create(Library::class)
32 | }
33 | }
34 |
35 | private val http = HttpClient(OkHttp) {
36 | CurlUserAgent()
37 | ContentEncoding()
38 | expectSuccess = true
39 | install(HttpTimeout) {
40 | connectTimeoutMillis = 30_000
41 | socketTimeoutMillis = 30_000
42 | }
43 | engine {
44 | config {
45 | dns(object : Dns {
46 | private val url = System.getProperty("xyz.cssxsh.mirai.doh", "https://public.dns.iij.jp/dns-query")
47 | private val doh = DnsOverHttps.Builder()
48 | .client(okhttp3.OkHttpClient())
49 | .url(url.toHttpUrl())
50 | .includeIPv6(true)
51 | .build()
52 | private val cn = listOf("repo.huaweicloud.com")
53 |
54 | @Throws(java.net.UnknownHostException::class)
55 | override fun lookup(hostname: String): List {
56 | if (hostname in cn) return Dns.SYSTEM.lookup(hostname)
57 | return try {
58 | doh.lookup(hostname)
59 | } catch (_: java.net.UnknownHostException) {
60 | Dns.SYSTEM.lookup(hostname)
61 | }
62 | }
63 | })
64 | }
65 | }
66 | }
67 |
68 | internal var listener: (urlString: String) -> ProgressListener? = { null }
69 |
70 | internal suspend fun download(urlString: String, folder: File): File {
71 | var name = urlString.substringAfterLast('/').decodeURLPart()
72 | .replace("""\d{13}-""".toRegex(), "")
73 | val listener = listener(name)
74 |
75 | val response = http.get(urlString) {
76 | onDownload(listener)
77 | }
78 | name = response.headers[HttpHeaders.ContentDisposition]
79 | ?.let { ContentDisposition.parse(it).parameter(ContentDisposition.Parameters.FileName) }
80 | ?: response.request.url.encodedPath.substringAfterLast('/').decodeURLPart()
81 | .replace("""\d{13}-""".toRegex(), "")
82 |
83 | val file = folder.resolve(name)
84 | val expect = response.contentLength()
85 |
86 | if (file.isFile && expect == file.length()) {
87 | logger.info { "文件 ${file.name} 已存在,跳过下载" }
88 | } else {
89 | file.delete()
90 | logger.info { "文件 ${file.name} 开始保存" }
91 | file.outputStream().use { output ->
92 | val channel = response.bodyAsChannel()
93 |
94 | while (!channel.isClosedForRead) channel.copyTo(output)
95 | }
96 | val actual = file.length()
97 | if (expect != null && actual != expect) {
98 | logger.warning { "${file.name} 下载异常 expect: $expect actual: $actual" }
99 | }
100 | }
101 | return file
102 | }
103 |
104 | /**
105 | * 下载字体到指定福利
106 | * @param folder 字体文件夹
107 | * @see loadTypeface
108 | */
109 | @JvmSynthetic
110 | public suspend fun downloadTypeface(folder: File, vararg links: String) {
111 | val downloaded: MutableList = ArrayList(links.size)
112 | val temp = runInterruptible(Dispatchers.IO) {
113 | Files.createTempDirectory("skia")
114 | .toFile()
115 | }
116 | temp.deleteOnExit()
117 | folder.mkdirs()
118 |
119 | for (link in links) {
120 | try {
121 | downloaded.add(download(urlString = link, folder = temp))
122 | } catch (cause: Exception) {
123 | logger.warning({ "字体下载失败, $link" }, cause)
124 | }
125 | }
126 |
127 | for (pack in downloaded) runInterruptible(Dispatchers.IO) {
128 | unpack(pack, folder)
129 | }
130 | }
131 |
132 | @JvmSynthetic
133 | public suspend fun downloadNotoEmoji(folder: File) {
134 | val temp = runInterruptible(Dispatchers.IO) {
135 | Files.createTempDirectory("skia")
136 | .toFile()
137 | }
138 | temp.deleteOnExit()
139 | folder.mkdirs()
140 |
141 | val link = "https://mirrors.tuna.tsinghua.edu.cn/github-release/googlefonts/noto-emoji/LatestRelease/repo-snapshot.tar.gz"
142 |
143 | val pack = try {
144 | download(urlString = link, folder = temp)
145 | } catch (cause: Exception) {
146 | logger.warning({ "字体下载失败, $link" }, cause)
147 | return
148 | }
149 | pack.inputStream()
150 | .buffered()
151 | .let(::GzipCompressorInputStream)
152 | .let(::TarArchiveInputStream)
153 | .use { input ->
154 | while (true) {
155 | val entry = input.nextEntry ?: break
156 | if (input.canReadEntryData(entry).not()) continue
157 | if (entry.name.endsWith("NotoColorEmoji_WindowsCompatible.ttf").not()) continue
158 | folder.mkdirs()
159 | val target = folder.resolve("NotoColorEmoji_WindowsCompatible.ttf")
160 | target.outputStream().use { output ->
161 | input.copyTo(output)
162 | }
163 | target.setLastModified(entry.modTime.time)
164 | }
165 | }
166 | }
167 |
168 | /**
169 | * 解压压缩包到指定文件夹
170 | * @param pack 压缩包
171 | * @param folder 文件夹
172 | */
173 | public fun unpack(pack: File, folder: File) {
174 | when (pack.extension) {
175 | "7z" -> SevenZFile.builder().setFile(pack).get().use { sevenZ ->
176 | for (entry in sevenZ.entries) {
177 | if (entry.isDirectory) continue
178 | if (entry.hasStream().not()) continue
179 | val target = folder.resolve(entry.name)
180 | if (target.extension !in FontExtensions) continue
181 | target.parentFile.mkdirs()
182 | target.outputStream().use { output ->
183 | sevenZ.getInputStream(entry).use { input ->
184 | input.copyTo(output)
185 | }
186 | }
187 | target.setLastModified(entry.lastModifiedDate.time)
188 | }
189 | }
190 | "zip" -> ZipFile(pack).use { zip ->
191 | for (entry in zip.entries()) {
192 | if (entry.isDirectory) continue
193 | if (entry.name.startsWith("__MACOSX")) continue
194 | val target = folder.resolve(entry.name)
195 | if (target.extension !in FontExtensions) continue
196 | target.parentFile.mkdirs()
197 | target.outputStream().use { output ->
198 | zip.getInputStream(entry).use { input ->
199 | input.copyTo(output)
200 | }
201 | }
202 | target.setLastModified(entry.lastModifiedTime.toMillis())
203 | }
204 | }
205 | "gz" -> pack.inputStream()
206 | .buffered()
207 | .let(::GzipCompressorInputStream)
208 | .let(::TarArchiveInputStream)
209 | .use { input ->
210 | while (true) {
211 | val entry = input.nextEntry ?: break
212 | if (entry.isFile.not()) continue
213 | if (input.canReadEntryData(entry).not()) continue
214 | val target = folder.resolve(entry.name)
215 | if (target.extension !in FontExtensions) continue
216 | target.parentFile.mkdirs()
217 | target.outputStream().use { output ->
218 | input.copyTo(output)
219 | }
220 | target.setLastModified(entry.modTime.time)
221 | }
222 | }
223 | else -> Files.move(pack.toPath(), folder.resolve(pack.name).toPath())
224 | }
225 | }
226 |
227 | /**
228 | * 从指定目录加载字体
229 | * @param folder 字体文件夹
230 | * @see FontUtils.loadTypeface
231 | */
232 | public fun loadTypeface(folder: File) {
233 | for (file in folder.listFiles() ?: return) {
234 | try {
235 | when (file.extension.lowercase()) {
236 | "ttf", "otf", "eot", "fon", "font", "woff", "woff2" -> FontUtils.loadTypeface(path = file.path)
237 | "ttc" -> {
238 | val count = file.inputStream().use { input ->
239 | input.skip(8)
240 | input.readNBytes(4).toInt()
241 | }
242 | for (index in 0 until count) {
243 | FontUtils.loadTypeface(path = file.path, index = index)
244 | }
245 | }
246 | else -> loadTypeface(folder = file)
247 | }
248 | } catch (cause: Exception) {
249 | logger.warning({ "加载字体文件失败 ${file.path}" }, cause)
250 | }
251 | }
252 | }
253 |
254 | /**
255 | * 字体后缀名
256 | */
257 | public val FontExtensions: Array = arrayOf("ttf", "otf", "eot", "fon", "font", "woff", "woff2", "ttc")
258 |
259 | /**
260 | * 一些免费字体链接
261 | */
262 | public val FreeFontLinks: Array = arrayOf(
263 | // "https://raw.githubusercontent.com/googlefonts/noto-emoji/main/fonts/NotoColorEmoji_WindowsCompatible.ttf",
264 | "https://mirai.mamoe.net/assets/uploads/files/1666870589379-方正书宋简体.ttf",
265 | "https://mirai.mamoe.net/assets/uploads/files/1666870589357-方正仿宋简体.ttf",
266 | "https://mirai.mamoe.net/assets/uploads/files/1666870589334-方正楷体简体.ttf",
267 | "https://mirai.mamoe.net/assets/uploads/files/1666870589312-方正黑体简体.ttf"
268 | )
269 |
270 | internal val SKIKO_MAVEN: String by lazy {
271 | System.getProperty("xyz.cssxsh.mirai.skiko.maven")
272 | ?: System.getProperty("xyz.cssxsh.mirai.skia.maven")
273 | ?: "https://maven.pkg.jetbrains.space/public/p/compose/dev"
274 | }
275 |
276 | internal val SKIKO_PACKAGE: String by lazy {
277 | System.getProperty("xyz.cssxsh.mirai.skiko.package")
278 | ?: System.getProperty("xyz.cssxsh.mirai.skia.package")
279 | ?: when {
280 | "android" in hostId -> "skiko-android-runtime-${hostArch.id}"
281 | else -> "skiko-awt-runtime-${hostId}"
282 | }
283 | }
284 |
285 | internal val SKIKO_VERSION: String by lazy {
286 | System.getProperty("xyz.cssxsh.mirai.skiko.version")
287 | ?: System.getProperty("xyz.cssxsh.mirai.skia.version")
288 | ?: Version.skiko
289 | }
290 |
291 | internal val GIF_RELEASE: String by lazy {
292 | System.getProperty("xyz.cssxsh.mirai.gif.release", "https://github.com/cssxsh/gif-jni")
293 | }
294 |
295 | internal val GIF_VERSION: String by lazy {
296 | System.getProperty("xyz.cssxsh.mirai.gif.version", xyz.cssxsh.gif.Version.gif)
297 | }
298 |
299 | private const val ICU = "icudtl.dat"
300 |
301 | /**
302 | * 检查平台问题并修正
303 | */
304 | public fun checkPlatform() {
305 | // Termux
306 | System.getenv("TERMUX_VERSION")?.let { version ->
307 | logger.info { "change platform: $hostId to android-arm64, for termux $version" }
308 | try {
309 | val kt = Class.forName("org.jetbrains.skiko.OsArch_jvmKt")
310 | val delegate = kt.getDeclaredField("hostId\$delegate").apply { isAccessible = true }
311 | val lazy = delegate.get(null)
312 | val value = lazy::class.java.getDeclaredField("_value").apply { isAccessible = true }
313 | value.set(lazy, "android-arm64")
314 | } catch (_: Exception) {
315 | logger.warning { "修改 hostId 失败" }
316 | }
317 | System.setProperty("xyz.cssxsh.mirai.skiko.version", "0.7.54")
318 | }
319 | }
320 |
321 | /**
322 | * 在 [folder] 中加载所需JNI库
323 | */
324 | public suspend fun loadJNILibrary(folder: File) {
325 | val skiko = System.mapLibraryName("skiko-$hostId")
326 | val gif = System.mapLibraryName("gif-$hostId")
327 |
328 | folder.mkdirs()
329 |
330 | with(folder.resolve(skiko)) {
331 | val version = folder.resolve("skia.version.txt")
332 | val maven = "$SKIKO_MAVEN/org/jetbrains/skiko/$SKIKO_PACKAGE/$SKIKO_VERSION/$SKIKO_PACKAGE-$SKIKO_VERSION.jar"
333 | val huawei = "https://repo.huaweicloud.com/repository/maven/org/jetbrains/skiko/$SKIKO_PACKAGE/$SKIKO_VERSION/$SKIKO_PACKAGE-$SKIKO_VERSION.jar"
334 | if (version.exists().not() || version.readText() != SKIKO_VERSION) delete()
335 |
336 | if (exists().not()) {
337 | val file = try {
338 | download(urlString = huawei, folder = folder)
339 | } catch (cause: ClientRequestException) {
340 | logger.warning({ huawei }, cause)
341 | try {
342 | download(urlString = maven, folder = folder)
343 | } catch (io: IOException) {
344 | throw io
345 | }
346 | }
347 | val jar = JarFile(file)
348 |
349 | outputStream().use { output ->
350 | jar.getInputStream(jar.getJarEntry(skiko)).transferTo(output)
351 | }
352 |
353 | if (hostOs == OS.Windows) {
354 | folder.resolve(ICU).outputStream().use { output ->
355 | jar.getInputStream(jar.getJarEntry(ICU)).transferTo(output)
356 | }
357 | }
358 |
359 | jar.close()
360 | file.deleteOnExit()
361 | }
362 | version.writeText(SKIKO_VERSION)
363 | }
364 | synchronized(System.getProperties()) {
365 | @Suppress("INVISIBLE_MEMBER")
366 | System.setProperty(Library.SKIKO_LIBRARY_PATH_PROPERTY, folder.path)
367 | Library.load()
368 | }
369 |
370 | with(folder.resolve(gif)) {
371 | val version = folder.resolve("gif.version.txt")
372 | val release = "$GIF_RELEASE/releases/download/v$GIF_VERSION/$gif"
373 | val proxy = "https://mirror.ghproxy.com/https://github.com/cssxsh/gif-jni/releases/download/v$GIF_VERSION/$gif"
374 | if (version.exists() && version.readText() != GIF_VERSION) delete()
375 |
376 | if (exists().not()) {
377 | try {
378 | download(urlString = proxy, folder = folder)
379 | } catch (cause: IOException) {
380 | logger.warning({ proxy }, cause)
381 | try {
382 | download(urlString = release, folder = folder)
383 | } catch (io: IOException) {
384 | throw io
385 | }
386 | }
387 | }
388 | version.writeText(GIF_VERSION)
389 | }
390 | System.setProperty(xyz.cssxsh.gif.Library.GIF_LIBRARY_PATH_PROPERTY, folder.path)
391 | xyz.cssxsh.gif.Library.load()
392 | }
--------------------------------------------------------------------------------
/src/main/kotlin/xyz/cssxsh/mirai/skia/MiraiSkiaPlugin.kt:
--------------------------------------------------------------------------------
1 | package xyz.cssxsh.mirai.skia
2 |
3 | import io.ktor.client.content.*
4 | import kotlinx.coroutines.*
5 | import net.mamoe.mirai.console.*
6 | import net.mamoe.mirai.console.extension.*
7 | import net.mamoe.mirai.console.plugin.jvm.*
8 | import net.mamoe.mirai.console.plugin.*
9 | import net.mamoe.mirai.console.util.*
10 | import net.mamoe.mirai.utils.*
11 | import org.jetbrains.skiko.*
12 | import xyz.cssxsh.skia.*
13 |
14 | /**
15 | * mirai-skia-plugin 插件主类
16 | */
17 | public object MiraiSkiaPlugin : KotlinPlugin(
18 | JvmPluginDescription(
19 | id = "xyz.cssxsh.mirai.plugin.mirai-skia-plugin",
20 | name = "mirai-skia-plugin",
21 | version = "1.3.2",
22 | ) {
23 | author("cssxsh")
24 | }
25 | ) {
26 |
27 | @OptIn(ConsoleExperimentalApi::class)
28 | internal val process: Closeable? by lazy {
29 | try {
30 | check(SemVersion.parseRangeRequirement("> 2.13.0").test(MiraiConsole.version))
31 | val impl = MiraiConsole.newProcessProgress()
32 | listener = { file ->
33 | val progress: ProgressListener = { total, contentLength ->
34 | when {
35 | contentLength == -1L -> {
36 | impl.updateText("<${file}> 下载中")
37 | }
38 | total >= contentLength -> {
39 | impl.updateText("<${file}> 下载完成")
40 | }
41 | else -> {
42 | val percentage = (total * 10000 / contentLength).toDouble() / 100.0
43 | impl.updateText("<${file}> 下载中 ${percentage}%")
44 | impl.update(total, contentLength)
45 | }
46 | }
47 | impl.rerender()
48 | }
49 |
50 | progress
51 | }
52 | impl
53 | } catch (_: Throwable) {
54 | null
55 | }
56 | }
57 |
58 | @PublishedApi
59 | internal val loadJob: Job = launch(start = CoroutineStart.LAZY) {
60 | checkPlatform()
61 | process
62 | try {
63 | loadJNILibrary(folder = resolveDataFile("lib"))
64 | val fonts = resolveDataFile("fonts")
65 | if (fonts.list().isNullOrEmpty()) {
66 | downloadTypeface(folder = fonts, links = FreeFontLinks)
67 | downloadNotoEmoji(folder = fonts)
68 | }
69 | } finally {
70 | listener = { null }
71 | runInterruptible(Dispatchers.IO) {
72 | process?.close()
73 | }
74 | }
75 | }
76 |
77 | override fun PluginComponentStorage.onLoad() {
78 | loadJob.invokeOnCompletion { cause ->
79 | val message = cause?.message
80 | if (cause is UnsatisfiedLinkError && message != null) {
81 | if (message.endsWith(": cannot open shared object file: No such file or directory")) {
82 | val lib = message.substringBeforeLast(": cannot open shared object file: No such file or directory")
83 | .substringAfterLast(": ")
84 | logger.warning { "可能缺少相应库文件,请参阅: https://pkgs.org/search/?q=${lib}" }
85 | }
86 | if (message.endsWith(": 无法打开共享对象文件: 没有那个文件或目录")) {
87 | val lib = message.substringBeforeLast(": 无法打开共享对象文件: 没有那个文件或目录")
88 | .substringAfterLast(": ")
89 | logger.warning { "可能缺少相应库文件,请参阅: https://pkgs.org/search/?q=${lib}" }
90 | }
91 | if ("GLIBC_" in message) {
92 | val version = message.substringAfterLast("version `")
93 | .substringBeforeLast("' not found")
94 | logger.warning { "可能缺少 ${version}, 请安装此版本 glibc" }
95 | }
96 | }
97 | if (message.orEmpty() == "Unknown arch x86") {
98 | logger.warning { "本插件不支持 32 位 JAVA!!!" }
99 | }
100 | }
101 | loadJob.start()
102 | }
103 |
104 | override fun onEnable() {
105 | // XXX: mirai console version check
106 | check(SemVersion.parseRangeRequirement(">= 2.12.0-RC").test(MiraiConsole.version)) {
107 | "$name $version 需要 Mirai-Console 版本 >= 2.12.0,目前版本是 ${MiraiConsole.version}"
108 | }
109 | logger.info { "platform: ${hostId}, skia: ${Version.skia}, skiko: ${Version.skiko}" }
110 | runBlocking {
111 | loadJob.join()
112 | }
113 | loadTypeface(folder = resolveDataFile("fonts"))
114 | logger.info { "fonts: ${FontUtils.provider.makeFamilies().keys}" }
115 | }
116 | }
--------------------------------------------------------------------------------
/src/main/kotlin/xyz/cssxsh/mirai/skia/SkiaExternalResource.kt:
--------------------------------------------------------------------------------
1 | package xyz.cssxsh.mirai.skia
2 |
3 | import net.mamoe.mirai.utils.*
4 | import org.jetbrains.skia.*
5 | import java.io.*
6 |
7 | /**
8 | * [ExternalResource] 关于 skia 的实现
9 | * @see ExternalResource
10 | */
11 | public class SkiaExternalResource(override val origin: Data, override val formatName: String) :
12 | ExternalResource, AbstractExternalResource({ origin.close() }) {
13 | public constructor(image: Image, format: EncodedImageFormat) : this(
14 | origin = requireNotNull(image.encodeToData(format)) { "encode $format result null." },
15 | formatName = format.name.replace("JPEG", "JPG")
16 | )
17 |
18 | override val md5: ByteArray by lazy { origin.bytes.md5() }
19 | override val sha1: ByteArray by lazy { origin.bytes.sha1() }
20 | override val size: Long get() = origin.size.toLong()
21 | override fun inputStream0(): InputStream = origin.bytes.inputStream()
22 | }
23 |
--------------------------------------------------------------------------------
/src/main/kotlin/xyz/cssxsh/mirai/skia/SkiaToMirai.kt:
--------------------------------------------------------------------------------
1 | package xyz.cssxsh.mirai.skia
2 |
3 | import net.mamoe.mirai.utils.*
4 | import org.jetbrains.skia.*
5 | import org.jetbrains.skia.svg.*
6 | import xyz.cssxsh.skia.*
7 | import java.io.*
8 |
9 | /**
10 | * 从 [Surface] 获取图片快照资源
11 | * @see Surface.makeImageSnapshot
12 | * @see ExternalResource
13 | */
14 | @JvmOverloads
15 | public fun Surface.makeSnapshotResource(format: EncodedImageFormat = EncodedImageFormat.PNG): SkiaExternalResource {
16 | return SkiaExternalResource(image = makeImageSnapshot(), format = format)
17 | }
18 |
19 | /**
20 | * 从 [File] 获取图片快照资源, 用于转换图片格式,例如 WEBP to PNG
21 | *
22 | * 注意: SVG 格式的矢量图 因为不一定包含 高度 和 宽度,所以不适用此方法, 可见 [SVGDOM.makeImageSnapshot]
23 | * @see Image.makeFromEncoded
24 | * @see ExternalResource
25 | */
26 | @JvmOverloads
27 | public fun File.makeImageResource(format: EncodedImageFormat = EncodedImageFormat.PNG): SkiaExternalResource {
28 | return SkiaExternalResource(image = Image.makeFromEncoded(bytes = this.readBytes()), format = format)
29 | }
30 |
31 | /**
32 | * 从 [Data] 获取图片资源
33 | *
34 | * @see ExternalResource
35 | */
36 | @JvmOverloads
37 | public fun Data.toImageResource(formatName: String = ExternalResource.DEFAULT_FORMAT_NAME): SkiaExternalResource {
38 | return SkiaExternalResource(origin = this, formatName = formatName)
39 | }
--------------------------------------------------------------------------------
/src/main/kotlin/xyz/cssxsh/skia/Canvas.kt:
--------------------------------------------------------------------------------
1 | package xyz.cssxsh.skia
2 |
3 | import org.jetbrains.skia.*
4 |
5 | /**
6 | * Canvas DSL, draw by [block]
7 | * @see Canvas.save
8 | * @see Canvas.restoreToCount
9 | */
10 | public inline fun Canvas.draw(crossinline block: Canvas.() -> Unit): Canvas {
11 | val index = save()
12 | try {
13 | block.invoke(this)
14 | } finally {
15 | restoreToCount(saveCount = index)
16 | }
17 | return this
18 | }
19 |
20 | /**
21 | * 调用 [Surface.canvas] 绘图
22 | * @see draw
23 | */
24 | public inline fun Surface.canvas(crossinline block: Canvas.() -> Unit): Canvas {
25 | return canvas.draw(block)
26 | }
--------------------------------------------------------------------------------
/src/main/kotlin/xyz/cssxsh/skia/Example.kt:
--------------------------------------------------------------------------------
1 | package xyz.cssxsh.skia
2 |
3 | import org.jetbrains.skia.*
4 | import org.jetbrains.skia.paragraph.*
5 | import xyz.cssxsh.gif.*
6 | import xyz.cssxsh.skia.gif.*
7 | import java.io.*
8 | import java.nio.file.*
9 |
10 | /**
11 | * 构造 PornPub Logo
12 | */
13 | public fun pornhub(porn: String = "Porn", hub: String = "Hub"): Surface {
14 | val font = Font(
15 | typeface = FontUtils.matchFamiliesStyle(arrayOf("Arial", "Noto Serif SC", "黑体"), FontStyle.BOLD),
16 | size = 90F
17 | )
18 | val prefix = TextLine.make(porn, font)
19 | val suffix = TextLine.make(hub, font)
20 | val black = Paint().setARGB(0xFF, 0x00, 0x00, 0x00)
21 | val white = Paint().setARGB(0xFF, 0xFF, 0xFF, 0xFF)
22 | val yellow = Paint().setARGB(0xFF, 0xFF, 0x90, 0x00)
23 |
24 | val surface = Surface.makeRasterN32Premul((prefix.width + suffix.width + 50).toInt(), (suffix.height + 40).toInt())
25 | surface.canvas {
26 | clear(black.color)
27 | drawTextLine(prefix, 10F, 20 - font.metrics.ascent, white)
28 | drawRRect(RRect.makeXYWH(prefix.width + 15, 15F, suffix.width + 20, suffix.height + 10, 10F), yellow)
29 | drawTextLine(suffix, prefix.width + 25, 20 - font.metrics.ascent, black)
30 | }
31 |
32 | return surface
33 | }
34 |
35 | public const val PET_PET_SPRITE: String = "xyz.cssxsh.skia.petpet"
36 |
37 | /**
38 | * 构造 PetPet Face
39 | *
40 | * [PetPet Sprite Image Download](https://benisland.neocities.org/petpet/img/sprite.png)
41 | * @see PET_PET_SPRITE
42 | */
43 | public fun petpet(face: Image, second: Double = 0.02): Data {
44 | val sprite = try {
45 | Image.makeFromEncoded(File(System.getProperty(PET_PET_SPRITE, "sprite.png")).readBytes())
46 | } catch (cause: IOException) {
47 | throw IllegalStateException(
48 | "please download https://benisland.neocities.org/petpet/img/sprite.png , file path set property $PET_PET_SPRITE",
49 | cause
50 | )
51 | }
52 | val surface = Surface.makeRasterN32Premul(112 * 5, 112)
53 | val rects = listOf(
54 | // 0, 0, 0, 0
55 | Rect.makeXYWH(21F, 21F, 91F, 91F),
56 | // -4, 12, 4, -12
57 | Rect.makeXYWH(112F + 21F - 4F, 21F + 12F, 91F + 4F, 91F - 12F),
58 | // -12, 18, 12, -18
59 | Rect.makeXYWH(224F + 21F - 12F, 21F + 18F, 91F + 12F, 91F - 18F),
60 | // -8, 12, 4, -12
61 | Rect.makeXYWH(336F + 21F - 8F, 21F + 12F, 91F + 4F, 91F - 12F),
62 | // -4, 0, 0, 0
63 | Rect.makeXYWH(448F + 21F - 4F, 21F, 91F, 91F)
64 | )
65 | val mode = FilterMipmap(FilterMode.LINEAR, MipmapMode.NEAREST)
66 | val source = Rect.makeWH(face.width.toFloat(), face.height.toFloat())
67 | val paint = Paint()
68 | paint.color = Color.WHITE
69 |
70 | surface.canvas {
71 | for (rect in rects) {
72 | paint.blendMode = BlendMode.SRC
73 | drawOval(
74 | r = rect,
75 | paint = paint
76 | )
77 |
78 | paint.blendMode = BlendMode.SRC_IN
79 | drawImageRect(
80 | image = face,
81 | src = source,
82 | dst = rect,
83 | samplingMode = mode,
84 | paint = paint,
85 | strict = true
86 | )
87 | }
88 |
89 | drawImage(sprite, 0F, 0F)
90 | }
91 |
92 | val images = (0 until 5).map { index ->
93 | val rect = IRect.makeXYWH(112 * index, 0, 112, 112)
94 | requireNotNull(surface.makeImageSnapshot(rect)) { "Make image snapshot fail" }
95 | }
96 |
97 | return gif(width = 112, height = 112) {
98 | table(bitmap = Bitmap.makeFromImage(surface.makeImageSnapshot()))
99 | loop(count = 0)
100 | options {
101 | duration = (second * 1000).toInt()
102 | disposalMethod = AnimationDisposalMode.RESTORE_BG_COLOR
103 | alphaType = ColorAlphaType.UNPREMUL
104 | }
105 | for (image in images) {
106 | frame(bitmap = Bitmap.makeFromImage(image))
107 | }
108 | }
109 | }
110 |
111 | /**
112 | * [5000choyen](https://github.com/yurafuca/5000choyen)
113 | */
114 | public fun choyen(top: String, bottom: String): Surface {
115 | val sans = Font(
116 | typeface = FontUtils.matchFamiliesStyle(arrayOf("Noto Sans SC", "FZHei-B01S", "MiSans"), FontStyle.BOLD),
117 | size = 100F
118 | )
119 | val serif = Font(
120 | typeface = FontUtils.matchFamiliesStyle(arrayOf("Noto Serif SC", "FZKai-Z03S", "MiSans"), FontStyle.BOLD),
121 | size = 100F
122 | )
123 | val red = TextLine.make(top, sans)
124 | val silver = TextLine.make(bottom, serif)
125 | val width = maxOf(red.textBlob!!.blockBounds.right + 70, silver.textBlob!!.blockBounds.right + 250).toInt()
126 | val surface = Surface.makeRasterN32Premul(width, 290)
127 | surface.canvas.skew(-0.45F, 0F)
128 | // top
129 | surface.canvas {
130 | val x = 70F
131 | val y = 100F
132 | val paint = Paint().setStroke(true)
133 |
134 | paint.strokeCap = PaintStrokeCap.ROUND
135 | paint.strokeJoin = PaintStrokeJoin.ROUND
136 | // 黒 22
137 | drawTextLine(red, x + 4, y + 4, paint.apply {
138 | shader = null
139 | color = Color.makeRGB(0, 0, 0)
140 | strokeWidth = 22F
141 | })
142 | // 銀 20
143 | drawTextLine(red, x + 4, y + 4, paint.apply {
144 | shader = Shader.makeLinearGradient(
145 | 0F, 24F, 0F, 122F, intArrayOf(
146 | Color.makeRGB(0, 15, 36),
147 | Color.makeRGB(255, 255, 255),
148 | Color.makeRGB(55, 58, 59),
149 | Color.makeRGB(55, 58, 59),
150 | Color.makeRGB(200, 200, 200),
151 | Color.makeRGB(55, 58, 59),
152 | Color.makeRGB(25, 20, 31),
153 | Color.makeRGB(240, 240, 240),
154 | Color.makeRGB(166, 175, 194),
155 | Color.makeRGB(50, 50, 50)
156 | ), floatArrayOf(0.0F, 0.10F, 0.18F, 0.25F, 0.5F, 0.75F, 0.85F, 0.91F, 0.95F, 1F)
157 | )
158 | strokeWidth = 20F
159 | })
160 | // 黒 16
161 | drawTextLine(red, x, y, paint.apply {
162 | shader = null
163 | color = Color.makeRGB(0, 0, 0)
164 | strokeWidth = 16F
165 | })
166 | // 金 10
167 | drawTextLine(red, x, y, paint.apply {
168 | shader = Shader.makeLinearGradient(
169 | 0F, 20F, 0F, 100F, intArrayOf(
170 | Color.makeRGB(253, 241, 0),
171 | Color.makeRGB(245, 253, 187),
172 | Color.makeRGB(255, 255, 255),
173 | Color.makeRGB(253, 219, 9),
174 | Color.makeRGB(127, 53, 0),
175 | Color.makeRGB(243, 196, 11),
176 | ), floatArrayOf(0.0F, 0.25F, 0.4F, 0.75F, 0.9F, 1F)
177 | )
178 | strokeWidth = 10F
179 | })
180 | // 黒 6
181 | drawTextLine(red, x + 2, y - 3, paint.apply {
182 | shader = null
183 | color = Color.makeRGB(0, 0, 0)
184 | strokeWidth = 6F
185 | })
186 | // 白 6
187 | drawTextLine(red, x, y - 3, paint.apply {
188 | shader = null
189 | color = Color.makeRGB(255, 255, 255)
190 | strokeWidth = 6F
191 | })
192 | // 赤 4
193 | drawTextLine(red, x, y - 3, paint.apply {
194 | shader = Shader.makeLinearGradient(
195 | 0F, 20F, 0F, 100F, intArrayOf(
196 | Color.makeRGB(255, 100, 0),
197 | Color.makeRGB(123, 0, 0),
198 | Color.makeRGB(240, 0, 0),
199 | Color.makeRGB(5, 0, 0),
200 | ), floatArrayOf(0.0F, 0.5F, 0.51F, 1F)
201 | )
202 | strokeWidth = 4F
203 | })
204 | // 赤
205 | drawTextLine(red, x, y - 3, paint.setStroke(false).apply {
206 | shader = Shader.makeLinearGradient(
207 | 0F, 20F, 0F, 100F, intArrayOf(
208 | Color.makeRGB(230, 0, 0),
209 | Color.makeRGB(123, 0, 0),
210 | Color.makeRGB(240, 0, 0),
211 | Color.makeRGB(5, 0, 0),
212 | ), floatArrayOf(0.0F, 0.5F, 0.51F, 1F)
213 | )
214 | })
215 | }
216 | // bottom
217 | surface.canvas {
218 | val x = 250F
219 | val y = 230F
220 | val paint = Paint().setStroke(true)
221 |
222 | paint.strokeCap = PaintStrokeCap.ROUND
223 | paint.strokeJoin = PaintStrokeJoin.ROUND
224 | // 黒
225 | drawTextLine(silver, x + 5, y + 2, paint.apply {
226 | shader = null
227 | color = Color.makeRGB(0, 0, 0)
228 | strokeWidth = 22F
229 | })
230 | // 銀
231 | drawTextLine(silver, x + 5, y + 2, paint.apply {
232 | shader = Shader.makeLinearGradient(
233 | 0F, y - 80, 0F, y + 18, intArrayOf(
234 | Color.makeRGB(0, 15, 36),
235 | Color.makeRGB(250, 250, 250),
236 | Color.makeRGB(150, 150, 150),
237 | Color.makeRGB(55, 58, 59),
238 | Color.makeRGB(25, 20, 31),
239 | Color.makeRGB(240, 240, 240),
240 | Color.makeRGB(166, 175, 194),
241 | Color.makeRGB(50, 50, 50)
242 | ), floatArrayOf(0.0F, 0.25F, 0.5F, 0.75F, 0.85F, 0.91F, 0.95F, 1F)
243 | )
244 | strokeWidth = 19F
245 | })
246 | // 黒
247 | drawTextLine(silver, x, y, paint.apply {
248 | shader = null
249 | color = Color.makeRGB(16, 25, 58)
250 | strokeWidth = 17F
251 | })
252 | // 白
253 | drawTextLine(silver, x, y, paint.apply {
254 | shader = null
255 | color = Color.makeRGB(221, 221, 221)
256 | strokeWidth = 8F
257 | })
258 | // 紺
259 | drawTextLine(silver, x, y, paint.apply {
260 | shader = Shader.makeLinearGradient(
261 | 0F, y - 80, 0F, y, intArrayOf(
262 | Color.makeRGB(16, 25, 58),
263 | Color.makeRGB(255, 255, 255),
264 | Color.makeRGB(16, 25, 58),
265 | Color.makeRGB(16, 25, 58),
266 | Color.makeRGB(16, 25, 58),
267 | ), floatArrayOf(0.0F, 0.03F, 0.08F, 0.2F, 1F)
268 | )
269 | strokeWidth = 7F
270 | })
271 | // 銀
272 | drawTextLine(silver, x, y - 3, paint.setStroke(false).apply {
273 | shader = Shader.makeLinearGradient(
274 | 0F, y - 80, 0F, y, intArrayOf(
275 | Color.makeRGB(245, 246, 248),
276 | Color.makeRGB(255, 255, 255),
277 | Color.makeRGB(195, 213, 220),
278 | Color.makeRGB(160, 190, 201),
279 | Color.makeRGB(160, 190, 201),
280 | Color.makeRGB(196, 215, 222),
281 | Color.makeRGB(255, 255, 255)
282 | ), floatArrayOf(0.0F, 0.15F, 0.35F, 0.5F, 0.51F, 0.52F, 1F)
283 | )
284 | strokeWidth = 19F
285 | })
286 | }
287 | return surface
288 | }
289 |
290 | public const val DEAR_ORIGIN: String = "xyz.cssxsh.skia.dear"
291 |
292 | /**
293 | * 构造 亲亲 表情
294 | * @see DEAR_ORIGIN
295 | * @return 临时文件
296 | */
297 | public fun dear(face: Image): File {
298 | val codec = try {
299 | Codec.makeFromData(Data.makeFromBytes(File(System.getProperty(DEAR_ORIGIN, "dear.gif")).readBytes()))
300 | } catch (cause: IOException) {
301 | throw IllegalStateException(
302 | "please download https://tva3.sinaimg.cn/large/003MWcpMly8gv4s019bzsg606o06o40902.gif , file path set property $DEAR_ORIGIN",
303 | cause
304 | )
305 | }
306 | val temp = Files.createTempFile("dear", "gif").toFile()
307 | val surface = Surface.makeRaster(codec.imageInfo)
308 | val bitmap = Bitmap().apply { allocPixels(codec.imageInfo) }
309 | val mode = FilterMipmap(FilterMode.LINEAR, MipmapMode.NEAREST)
310 | val src = Rect.makeWH(face.width.toFloat(), face.height.toFloat())
311 | val rects = listOf(
312 | Rect.makeXYWH(48F, 118F, 60F, 60F),
313 | Rect.makeXYWH(70F, 110F, 55F, 60F),
314 | Rect.makeXYWH(78F, 108F, 55F, 65F),
315 | Rect.makeXYWH(54F, 125F, 60F, 60F),
316 | Rect.makeXYWH(65F, 121F, 60F, 70F),
317 | Rect.makeXYWH(69F, 121F, 56F, 66F),
318 | Rect.makeXYWH(24F, 148F, 56F, 56F),
319 | Rect.makeXYWH(30F, 130F, 70F, 60F),
320 | Rect.makeXYWH(75F, 110F, 50F, 70F),
321 | Rect.makeXYWH(56F, 120F, 50F, 60F),
322 | Rect.makeXYWH(75F, 118F, 60F, 65F),
323 | Rect.makeXYWH(46F, 136F, 55F, 70F),
324 | Rect.makeXYWH(23F, 151F, 68F, 58F),
325 | )
326 | val paint = Paint()
327 | paint.color = Color.WHITE
328 |
329 | Encoder(temp, surface.width, surface.height).use { encoder ->
330 | encoder.repeat = -1
331 | for (index in 0 until codec.frameCount) {
332 | codec.readPixels(bitmap, index)
333 | surface.writePixels(bitmap, 0, 0)
334 | surface.canvas {
335 | paint.blendMode = BlendMode.SRC_OUT
336 | drawOval(
337 | r = rects[index],
338 | paint = paint
339 | )
340 |
341 | paint.blendMode = BlendMode.DST_OVER
342 | drawImageRect(
343 | image = face,
344 | src = src,
345 | dst = rects[index],
346 | samplingMode = mode,
347 | paint = paint,
348 | strict = false
349 | )
350 | }
351 |
352 | val info = codec.getFrameInfo(index)
353 | val image = surface.makeImageSnapshot()
354 | encoder.writeImage(image, info.duration, info.disposalMethod)
355 | }
356 | }
357 |
358 | return temp
359 | }
360 |
361 | public const val ZZKIA_ORIGIN: String = "xyz.cssxsh.skia.zzkia"
362 |
363 | /**
364 | * [zzkia](https://github.com/dcalsky/zzkia)
365 | * @see ZZKIA_ORIGIN
366 | */
367 | public fun zzkia(text: String): Surface {
368 | val origin = try {
369 | Image.makeFromEncoded(File(System.getProperty(ZZKIA_ORIGIN, "zzkia.jpg")).readBytes())
370 | } catch (cause: IOException) {
371 | throw IllegalStateException(
372 | "please download https://cdn.jsdelivr.net/gh/dcalsky/bbq/zzkia/images/4.jpg , file path set property $ZZKIA_ORIGIN",
373 | cause
374 | )
375 | }
376 | val surface = Surface.makeRaster(origin.imageInfo)
377 | surface.writePixels(Bitmap.makeFromImage(origin), 0, 0)
378 |
379 | surface.canvas.rotate(9.8F)
380 |
381 | val fonts = FontCollection()
382 | .setDynamicFontManager(FontUtils.provider)
383 | .setDefaultFontManager(FontMgr.default, "FZXS14")
384 | val families = arrayOf("FZXS14", "FZKai-Z03S")
385 |
386 | // context
387 | val context = ParagraphStyle().apply {
388 | textStyle = TextStyle()
389 | .setFontSize(70F)
390 | .setColor(Color.BLACK)
391 | .setFontFamilies(families)
392 |
393 | maxLinesCount = 7
394 | }
395 | ParagraphBuilder(context, fonts)
396 | .addText(text)
397 | .build()
398 | .layout(700F)
399 | .paint(surface.canvas, 330F, 270F)
400 |
401 | // count
402 | val count = ParagraphStyle().apply {
403 | alignment = Alignment.RIGHT
404 | textStyle = TextStyle()
405 | .setFontSize(70F)
406 | .setColor(Color.makeARGB(255, 129, 212, 250))
407 | .setFontFamilies(families)
408 | }
409 | ParagraphBuilder(count, fonts)
410 | .addText("${text.length}/900")
411 | .build()
412 | .layout(680F)
413 | .paint(surface.canvas, 360F, 170F)
414 |
415 | return surface
416 | }
417 |
418 | /**
419 | * [幻影坦克](https://samarium150.github.io/mirage-tank-images/)
420 | */
421 | public fun tank(top: Image, bottom: Image): Surface {
422 | val surface = Surface.makeRasterN32Premul(top.width, top.height)
423 | val canvas = surface.canvas
424 | val paint = Paint()
425 | paint.reset()
426 |
427 | // val gray = ColorFilter.makeMatrix(
428 | // ColorMatrix(
429 | // 0.299F, 0.587F, 0.114F, 0F, 0F, // red
430 | // 0.299F, 0.587F, 0.114F, 0F, 0F, // green
431 | // 0.299F, 0.587F, 0.114F, 0F, 0F, // blue
432 | // 0F, 0F, 0F, 0F, 1F
433 | // )
434 | // )
435 |
436 | canvas.clear(Color.TRANSPARENT)
437 | paint.reset()
438 | paint.colorFilter = ColorFilter.makeMatrix(
439 | ColorMatrix(
440 | 0.5F, 0F, 0F, 0F, 0.5F, // red
441 | 0F, 0.5F, 0F, 0F, 0.5F, // green
442 | 0F, 0F, 0.5F, 0F, 0.5F, // blue
443 | 0F, 0F, 0F, 0F, 1F
444 | )
445 | )
446 | canvas.drawImage(top, 0F, 0F, paint)
447 | val a = surface.makeImageSnapshot()
448 |
449 | canvas.clear(Color.TRANSPARENT)
450 | paint.reset()
451 | paint.colorFilter = ColorFilter.makeMatrix(
452 | ColorMatrix(
453 | 0.5F, 0F, 0F, 0F, 0F, // red
454 | 0F, 0.5F, 0F, 0F, 0F, // green
455 | 0F, 0F, 0.5F, 0F, 0F, // blue
456 | 0F, 0F, 0F, 0F, 1F
457 | )
458 | )
459 | val rect = if (top.width * bottom.height > bottom.width * top.height) {
460 | val width = bottom.width.toFloat().times(top.height).div(bottom.height)
461 | Rect.makeXYWH(
462 | top.width.minus(width).div(2),
463 | 0F,
464 | width,
465 | top.height.toFloat()
466 | )
467 | } else {
468 | val height = bottom.height.toFloat().times(top.width).div(bottom.width)
469 | Rect.makeXYWH(
470 | 0F,
471 | top.height.minus(height).div(2),
472 | top.width.toFloat(),
473 | height
474 | )
475 | }
476 | canvas.drawImageRect(bottom, rect, paint)
477 | val b = surface.makeImageSnapshot()
478 |
479 | canvas.clear(Color.TRANSPARENT)
480 | paint.reset()
481 | paint.colorFilter = ColorFilter.makeMatrix(
482 | ColorMatrix(
483 | -1F, 0F, 0F, 0F, 1F, // red
484 | 0F, -1F, 0F, 0F, 1F, // green
485 | 0F, 0F, -1F, 0F, 1F, // blue
486 | 0F, 0F, 0F, 0F, 1F
487 | )
488 | )
489 | canvas.drawImage(a, 0F, 0F, paint)
490 | paint.reset()
491 | paint.blendMode = BlendMode.PLUS
492 | canvas.drawImage(b, 0F, 0F, paint)
493 | val o = surface.makeImageSnapshot()
494 |
495 | canvas.clear(Color.TRANSPARENT)
496 | paint.reset()
497 | val dsc = Bitmap.makeFromImage(o)
498 | val src = Bitmap.makeFromImage(b)
499 | repeat(o.width) { x ->
500 | repeat(o.height) { y ->
501 | val s = Color4f(dsc.getColor(x, y))
502 | val t = Color4f(src.getColor(x, y))
503 |
504 | val g1 = (s.r + s.g + s.b) / 3
505 | val g2 = (t.r + t.g + t.b) / 3
506 | val g3 = g2 / g1
507 |
508 | val r = Color4f(g3, g3, g3, g1)
509 | paint.color4f = r
510 |
511 | canvas.drawPoint(x.toFloat(), y.toFloat(), paint)
512 | }
513 | }
514 | // paint.reset()
515 | // canvas.drawImage(o, 0F, 0F, paint)
516 | // paint.blendMode = BlendMode.DIFFERENCE
517 | // canvas.drawImage(b, 0F, 0F, paint)
518 |
519 | return surface
520 | }
--------------------------------------------------------------------------------
/src/main/kotlin/xyz/cssxsh/skia/Font.kt:
--------------------------------------------------------------------------------
1 | package xyz.cssxsh.skia
2 |
3 | import org.jetbrains.skia.*
4 |
5 | /**
6 | * 获取字体管理器中的字体家族
7 | */
8 | public fun FontMgr.makeFamilies(): Map {
9 | val count = familiesCount
10 | if (count == 0) return emptyMap()
11 | val families: MutableMap = HashMap()
12 |
13 | for (index in 0 until count) {
14 | val name = getFamilyName(index)
15 | val styles = makeStyleSet(index) ?: throw NoSuchElementException("${this}: ${index}.${name}")
16 | families[name] = styles
17 | }
18 |
19 | return families
20 | }
--------------------------------------------------------------------------------
/src/main/kotlin/xyz/cssxsh/skia/FontUtils.kt:
--------------------------------------------------------------------------------
1 | package xyz.cssxsh.skia
2 |
3 | import org.jetbrains.skia.*
4 | import org.jetbrains.skia.paragraph.*
5 | import java.util.*
6 | import kotlin.collections.*
7 | import kotlin.jvm.*
8 |
9 | /**
10 | * 获取字体工具
11 | * @see Typeface
12 | * @see FontMgr
13 | * @see TypefaceFontProvider
14 | * @see [https://docs.microsoft.com/en-us/typography/fonts/windows_10_font_list]
15 | */
16 | public object FontUtils {
17 |
18 | @PublishedApi
19 | internal val instances: Sequence = sequence {
20 | yield(provider)
21 | yield(FontMgr.default)
22 | yieldAll(ServiceLoader.load(FontMgr::class.java))
23 | yieldAll(ServiceLoader.load(TypefaceFontProvider::class.java))
24 | }
25 |
26 | public val provider: TypefaceFontProvider = TypefaceFontProvider()
27 |
28 | /**
29 | * 字体列表
30 | */
31 | public fun families(): Set {
32 | val names: MutableSet = HashSet()
33 | for (manager in instances) {
34 | repeat(manager.familiesCount) { index -> names.add(manager.getFamilyName(index)) }
35 | }
36 |
37 | return names
38 | }
39 |
40 | /**
41 | * 加载字体
42 | * @see provider
43 | */
44 | public fun loadTypeface(path: String, index: Int = 0) {
45 | provider.registerTypeface(Typeface.makeFromFile(path, index))
46 | }
47 |
48 | /**
49 | * 加载字体
50 | * @see provider
51 | */
52 | public fun loadTypeface(data: Data, index: Int = 0) {
53 | provider.registerTypeface(Typeface.makeFromData(data, index))
54 | }
55 |
56 | /**
57 | * 加载字体
58 | * @see provider
59 | */
60 | public fun loadTypeface(bytes: ByteArray, index: Int = 0) {
61 | Data.makeFromBytes(bytes).use { data -> loadTypeface(data, index) }
62 | }
63 |
64 | /**
65 | * 获取指定的 [Typeface]
66 | */
67 | public fun matchFamilyStyle(familyName: String, style: FontStyle): Typeface? {
68 | for (provider in instances) {
69 | return provider.matchFamily(familyName).matchStyle(style) ?: continue
70 | }
71 | return null
72 | }
73 |
74 | /**
75 | * 获取指定的 [Typeface]
76 | */
77 | public fun matchFamiliesStyle(families: Array, style: FontStyle): Typeface? {
78 | for (provider in instances) {
79 | for (familyName in families) {
80 | return provider.matchFamily(familyName).matchStyle(style) ?: continue
81 | }
82 | }
83 | return null
84 | }
85 |
86 | /**
87 | * 获取指定的 [FontStyleSet] (count != 0)
88 | */
89 | public fun matchFamily(familyName: String): FontStyleSet? {
90 | for (provider in instances) {
91 | val styles = provider.matchFamily(familyName)
92 | if (styles.count() != 0) {
93 | return styles
94 | }
95 | }
96 | return null
97 | }
98 |
99 | /**
100 | * 宋体
101 | */
102 | public fun matchSimSun(style: FontStyle): Typeface? = matchFamilyStyle("SimSun", style)
103 |
104 | /**
105 | * 新宋体
106 | */
107 | public fun matchNSimSun(style: FontStyle): Typeface? = matchFamilyStyle("NSimSun", style)
108 |
109 | /**
110 | * 黑体
111 | */
112 | public fun matchSimHei(style: FontStyle): Typeface? = matchFamilyStyle("SimHei", style)
113 |
114 | /**
115 | * 仿宋
116 | */
117 | public fun matchFangSong(style: FontStyle): Typeface? = matchFamilyStyle("FangSong", style)
118 |
119 | /**
120 | * 楷体
121 | */
122 | public fun matchKaiTi(style: FontStyle): Typeface? = matchFamilyStyle("KaiTi", style)
123 |
124 | /**
125 | * Arial
126 | */
127 | public fun matchArial(style: FontStyle): Typeface? = matchFamilyStyle("Arial", style)
128 |
129 | /**
130 | * Calibri
131 | */
132 | public fun matchCalibri(style: FontStyle): Typeface? = matchFamilyStyle("Calibri", style)
133 |
134 | /**
135 | * Consolas
136 | */
137 | public fun matchConsolas(style: FontStyle): Typeface? = matchFamilyStyle("Consolas", style)
138 |
139 | /**
140 | * Times New Roman
141 | */
142 | public fun matchTimesNewRoman(style: FontStyle): Typeface? = matchFamilyStyle("Times New Roman", style)
143 |
144 | /**
145 | * Helvetica
146 | */
147 | public fun matchHelvetica(style: FontStyle): Typeface? = matchFamilyStyle("Helvetica", style)
148 |
149 | /**
150 | * Liberation Sans
151 | */
152 | public fun matchLiberationSans(style: FontStyle): Typeface? = matchFamilyStyle("Liberation Sans", style)
153 |
154 | /**
155 | * Liberation Serif
156 | */
157 | public fun matchLiberationSerif(style: FontStyle): Typeface? = matchFamilyStyle("Liberation Serif", style)
158 |
159 | /**
160 | * Noto Color Emoji
161 | */
162 | public fun matchNotoColorEmoji(style: FontStyle): Typeface? = matchFamilyStyle("Noto Color Emoji", style)
163 | }
--------------------------------------------------------------------------------
/src/main/kotlin/xyz/cssxsh/skia/Mosaic.kt:
--------------------------------------------------------------------------------
1 | package xyz.cssxsh.skia
2 |
3 | import org.jetbrains.skia.*
4 | import kotlin.math.pow
5 | import kotlin.reflect.full.*
6 |
7 | /**
8 | * 马赛克构建器
9 | */
10 | public sealed class MosaicOption {
11 | internal abstract fun convert(bitmap: Bitmap)
12 |
13 | /**
14 | * 三角形马赛克
15 | * @param side 边长
16 | */
17 | public data class Rectangle(var side: Int = 10) : MosaicOption() {
18 | override fun convert(bitmap: Bitmap) {
19 | val offset = side
20 | for (x in 0 until bitmap.width step offset) {
21 | for (y in 0 until bitmap.height step offset) {
22 | val colors = listOf(
23 | bitmap.getColor(x, y),
24 | bitmap.getColor(x + side - 1, y),
25 | bitmap.getColor(x, y + side - 1),
26 | bitmap.getColor(x + side - 1, y + side - 1)
27 | )
28 | val color = Color.makeARGB(
29 | a = colors.sumOf { Color.getA(it) } / 4,
30 | r = colors.sumOf { Color.getR(it) } / 4,
31 | g = colors.sumOf { Color.getG(it) } / 4,
32 | b = colors.sumOf { Color.getB(it) } / 4
33 | )
34 | bitmap.erase(color, IRect.makeXYWH(x, y, side, side))
35 | }
36 | }
37 | }
38 | }
39 |
40 | /**
41 | * 六边形马赛克
42 | * @param side 边长
43 | */
44 | public data class Hexagon(var side: Int = 10) : MosaicOption() {
45 | private fun up(bitmap: Bitmap, x: Int, y: Int, width: Int, height: Int) {
46 | val left = bitmap.getColor(x, y)
47 | val right = bitmap.getColor(
48 | (x + width).coerceAtMost(bitmap.width - 1),
49 | (y + height).coerceAtMost(bitmap.height - 1)
50 | )
51 | for (offset in 0 until width) {
52 | val h = ((side - offset) * 3.0.pow(0.5)).toInt().coerceAtMost(height).coerceAtLeast(0)
53 | if (h > 0) {
54 | bitmap.erase(left, IRect.makeXYWH(x + offset, y, 1, h))
55 | }
56 | if (h < height) {
57 | bitmap.erase(right, IRect.makeXYWH(x + offset, y + h, 1, height - h))
58 | }
59 | }
60 | }
61 |
62 | private fun down(bitmap: Bitmap, x: Int, y: Int, width: Int, height: Int) {
63 | val left = bitmap.getColor(x, (y + height).coerceAtMost(bitmap.height - 1))
64 | val right = bitmap.getColor((x + width).coerceAtMost(bitmap.width - 1), y)
65 | for (offset in 0 until width) {
66 | val h = ((side - offset) * 3.0.pow(0.5)).toInt().coerceAtMost(height).coerceAtLeast(0)
67 | if (h > 0) {
68 | bitmap.erase(left, IRect.makeXYWH(x + offset, y + height - h, 1, h))
69 | }
70 | if (h < height) {
71 | bitmap.erase(right, IRect.makeXYWH(x + offset, y, 1, height - h))
72 | }
73 | }
74 | }
75 |
76 | override fun convert(bitmap: Bitmap) {
77 | val width = (side * 1.5).toInt()
78 | val height = (side * 0.5 * 3.0.pow(0.5)).toInt()
79 | var case = 0
80 |
81 | for (x in 0 until bitmap.width step width) {
82 | for (y in 0 until bitmap.height step height) {
83 | when (case) {
84 | 0, 2 -> up(bitmap, x, y, width, height)
85 | 1, 3 -> down(bitmap, x, y, width, height)
86 | }
87 |
88 | case = case xor 0x1
89 | }
90 | case = case xor 0x2
91 | }
92 | }
93 | }
94 | }
95 |
96 | /**
97 | * 绘制马赛克
98 | * @param area 绘制区域
99 | * @param options 马赛克绘制器
100 | */
101 | public fun Surface.drawMosaic(area: IRect, options: MosaicOption) {
102 | val bitmap = Bitmap()
103 |
104 | bitmap.allocPixels(imageInfo.withWidthHeight(area.width, area.height))
105 | readPixels(bitmap, area.left, area.top)
106 | // 心里有码,则万物有码
107 | options.convert(bitmap)
108 | writePixels(bitmap, area.left, area.top)
109 | }
110 |
111 | /**
112 | * 绘制马赛克
113 | * @param area 绘制区域
114 | */
115 | public inline fun Surface.drawMosaic(area: IRect, block: O.() -> Unit = {}) {
116 | drawMosaic(area = area, options = O::class.createInstance().apply(block))
117 | }
--------------------------------------------------------------------------------
/src/main/kotlin/xyz/cssxsh/skia/SVGDOM.kt:
--------------------------------------------------------------------------------
1 | package xyz.cssxsh.skia
2 |
3 | import org.jetbrains.skia.*
4 | import org.jetbrains.skia.svg.*
5 | import org.jsoup.nodes.*
6 | import org.jsoup.parser.*
7 | import org.jsoup.select.*
8 | import java.io.*
9 |
10 | /**
11 | * 从 xml 读取 SVGDOM
12 | * @see org.jsoup.parser.Parser
13 | * @see SVGDOM.Companion.makeFromXml
14 | */
15 | public fun SVGDOM.Companion.makeFromString(xml: String, baseUri: String = ""): SVGDOM {
16 | return makeFromXml(document = Parser.xmlParser().parseInput(xml, baseUri))
17 | }
18 |
19 | /**
20 | * 从 file 读取 SVGDOM
21 | * @see org.jsoup.parser.Parser
22 | * @see SVGDOM.Companion.makeFromXml
23 | */
24 | public fun SVGDOM.Companion.makeFromFile(xml: File, baseUri: String = ""): SVGDOM {
25 | return makeFromXml(document = xml.bufferedReader().use { Parser.xmlParser().parseInput(it, baseUri) })
26 | }
27 |
28 | /**
29 | * 将 Style 写入具体的 Element 中,修正SVG绘图结果
30 | * @see SVGDOM.Companion.makeFromString
31 | */
32 | public fun SVGDOM.Companion.makeFromXml(document: Document): SVGDOM {
33 | for (style in document.select("style").remove()) {
34 | document.apply(css = style.text())
35 | }
36 |
37 | return SVGDOM(data = Data.makeFromBytes(bytes = document.toString().toByteArray()))
38 | }
39 |
40 | private const val CSS_FONT_REGEX =
41 | """font:\s*(normal|italic|oblique|inherit|)\s*(normal|small-caps|inherit|)\s*(normal|bold|bolder|inherit|\d+|)\s+([^/ ]+)/?(\S*)\s+(.+);"""
42 |
43 | /**
44 | * 将 [css] 生效
45 | */
46 | private fun Document.apply(css: String) {
47 | var pos = 0
48 |
49 | while (true) {
50 | val before = css.indexOf('{', pos)
51 | if (before == -1) break
52 | val after = css.indexOf('}', before)
53 | if (after == -1) break
54 |
55 | val query = css.substring(pos, before)
56 | val value = css.substring(before + 1, after)
57 | .replace(CSS_FONT_REGEX.toRegex()) { match ->
58 | // fixme: font: ...
59 | val (style, variant, weight, size, height, family) = match.destructured
60 | buildString {
61 | if (style.isNotEmpty()) append("font-style: ").append(style).append("; ")
62 | if (variant.isNotEmpty()) append("font-variant: ").append(variant).append("; ")
63 | if (weight.isNotEmpty()) append("font-weight: ").append(weight).append("; ")
64 | append("font-size: ").append(size).append("; ")
65 | if (height.isNotEmpty()) append("line-height: ").append(height).append("; ")
66 | append("font-family: ").append(family).append("; ")
67 | }
68 | }
69 | val elements = try {
70 | select(query)
71 | } catch (_: Selector.SelectorParseException) {
72 | emptyList()
73 | }
74 |
75 | for (element in elements) {
76 | element.attr("style", value + element.attr("style"))
77 | }
78 |
79 | pos = after + 1
80 | }
81 | }
82 |
83 | /**
84 | * @see SVGDOM.setContainerSize
85 | */
86 | public fun SVGDOM.makeImageSnapshot(width: Int, height: Int): Image {
87 | setContainerSize(width.toFloat(), height.toFloat())
88 |
89 | return Surface.makeRasterN32Premul(width, height).use { surface ->
90 | render(surface.canvas)
91 | surface.makeImageSnapshot()
92 | }
93 | }
--------------------------------------------------------------------------------
/src/main/kotlin/xyz/cssxsh/skia/Style.kt:
--------------------------------------------------------------------------------
1 | @file:JvmName("StyleUtils")
2 |
3 | package xyz.cssxsh.skia
4 |
5 | import org.jetbrains.skia.*
6 | import org.jetbrains.skia.impl.*
7 |
8 | /**
9 | * 生成 LobPoly 风格 位图
10 | * @param variance 方差 [0.0, 1.0]
11 | * @param cellSize 单元格大小 [0.0, 1.0]
12 | * @param depth 深度
13 | * @param dither 抖动
14 | * @param seed 种子
15 | */
16 | public fun Bitmap.generateLowPoly(
17 | variance: Double,
18 | cellSize: Int,
19 | depth: Int,
20 | dither: Int,
21 | seed: Int
22 | ): Bitmap {
23 | require(variance in 0.0..1.0) { "variance need in 0.0 .. 1.0" }
24 | require(cellSize > 0) { "cell size need in 0.0 .. 1.0" }
25 | require(depth > 0) { "depth need > 0" }
26 | require(dither > 0) { "dither need > 0" }
27 | @Suppress("INVISIBLE_MEMBER")
28 | renderLowPoly(variance, cellSize, depth, dither, seed, _ptr)
29 | return this
30 | }
31 |
32 | internal external fun renderLowPoly(
33 | variance: Double,
34 | cellSize: Int,
35 | depth: Int,
36 | dither: Int,
37 | seed: Int,
38 | bitmap: NativePointer
39 | ): NativePointer
--------------------------------------------------------------------------------
/src/main/kotlin/xyz/cssxsh/skia/gif/ApplicationExtension.kt:
--------------------------------------------------------------------------------
1 | package xyz.cssxsh.skia.gif
2 |
3 | import java.nio.*
4 |
5 | /**
6 | * GIF Application Extension Info 写入器
7 | */
8 | public object ApplicationExtension {
9 | private const val INTRODUCER = 0x21
10 | private const val LABEL = 0xFF
11 | private const val BLOCK_SIZE = 0x0B
12 | private const val TERMINATOR = 0x00
13 |
14 | private fun block(
15 | buffer: ByteBuffer,
16 | identifier: ByteArray,
17 | authentication: ByteArray,
18 | data: ByteArray,
19 | ) {
20 | buffer.put(INTRODUCER.asUnsignedByte())
21 | buffer.put(LABEL.asUnsignedByte())
22 | buffer.put(BLOCK_SIZE.asUnsignedByte())
23 | buffer.put(identifier) // 8 byte
24 | buffer.put(authentication) // 3 byte
25 | buffer.put(data.size.asUnsignedByte())
26 | buffer.put(data)
27 | buffer.put(TERMINATOR.asUnsignedByte())
28 | }
29 |
30 | private fun write(buffer: ByteBuffer, identifier: String, authentication: String, data: ByteArray) {
31 | block(
32 | buffer = buffer,
33 | identifier = identifier.toByteArray(Charsets.US_ASCII),
34 | authentication = authentication.toByteArray(Charsets.US_ASCII),
35 | data = data
36 | )
37 | }
38 |
39 | /**
40 | * 循环
41 | * @param buffer 写入的目标
42 | * @param count 循环次数
43 | */
44 | public fun loop(buffer: ByteBuffer, count: Int) {
45 | write(
46 | buffer = buffer,
47 | identifier = "NETSCAPE",
48 | authentication = "2.0",
49 | data = byteArrayOf(
50 | 0x01,
51 | count.ushr(8).toByte(),
52 | count.ushr(0).toByte()
53 | )
54 | )
55 | }
56 |
57 | /**
58 | * 启用缓存
59 | * @param buffer 写入的目标
60 | * @param capacity 缓存块容量
61 | */
62 | public fun buffering(buffer: ByteBuffer, capacity: Int) {
63 | write(
64 | buffer = buffer,
65 | identifier = "NETSCAPE",
66 | authentication = "2.0",
67 | data = byteArrayOf(
68 | 0x01,
69 | capacity.ushr(24).toByte(),
70 | capacity.ushr(16).toByte(),
71 | capacity.ushr(8).toByte(),
72 | capacity.ushr(0).toByte()
73 | )
74 | )
75 | }
76 |
77 | /**
78 | * 简介信息
79 | * @param buffer 写入的目标
80 | * @param data 简介数据
81 | */
82 | public fun profile(buffer: ByteBuffer, data: ByteArray) {
83 | write(
84 | buffer = buffer,
85 | identifier = "ICCRGBG1",
86 | authentication = "012",
87 | data = data
88 | )
89 | }
90 | }
--------------------------------------------------------------------------------
/src/main/kotlin/xyz/cssxsh/skia/gif/AtkinsonDitherer.kt:
--------------------------------------------------------------------------------
1 | package xyz.cssxsh.skia.gif
2 |
3 | import org.jetbrains.skia.*
4 |
5 | /**
6 | * Atkinson 算法 抖动器
7 | */
8 | public object AtkinsonDitherer {
9 | private val DISTRIBUTION: List = listOf(
10 | ErrorComponent(1, 0, 1 / 8.0),
11 | ErrorComponent(2, 0, 1 / 8.0),
12 |
13 | ErrorComponent(-1, 1, 1 / 8.0),
14 | ErrorComponent(0, 1, 1 / 8.0),
15 | ErrorComponent(1, 1, 1 / 8.0),
16 |
17 | ErrorComponent(0, 2, 1 / 8.0),
18 | )
19 |
20 | private data class ErrorComponent(
21 | val deltaX: Int,
22 | val deltaY: Int,
23 | val power: Double
24 | )
25 |
26 | private data class Color(val red: Int, val green: Int, val blue: Int) {
27 | constructor(rgb: Int) : this(
28 | red = rgb and 0xFF0000 shr 16,
29 | green = rgb and 0x00FF00 shr 8,
30 | blue = rgb and 0x0000FF
31 | )
32 | }
33 |
34 | private operator fun Color.minus(other: Color): Color =
35 | Color(this.red - other.red, this.green - other.green, this.blue - other.blue)
36 |
37 | private operator fun Color.plus(other: Color): Color =
38 | Color(this.red + other.red, this.green + other.green, this.blue + other.blue)
39 |
40 | private operator fun Color.times(power: Double): Color =
41 | Color((this.red * power).toInt(), (this.green * power).toInt(), (this.blue * power).toInt())
42 |
43 | private fun Color.nearest(): Int = red * red + green * green + blue * blue
44 |
45 | /**
46 | * 计算抖动
47 | * @param bitmap 位图
48 | * @param table 调色板
49 | * @return 抖动结果
50 | */
51 | public fun dither(bitmap: Bitmap, table: IntArray): IntArray {
52 | val width = bitmap.width
53 | val height = bitmap.height
54 | val colors = Array(height) { y -> Array(width) { x -> Color(rgb = bitmap.getColor(x, y)) } }
55 | val tableColors = List(table.size) { index -> Color(rgb = table[index]) }
56 |
57 | for (y in 0 until height) {
58 | for (x in 0 until width) {
59 | val original = colors[y][x]
60 | val replacement = tableColors.minByOrNull { (it - original).nearest() }!!
61 | colors[y][x] = replacement
62 | val error = original - replacement
63 | for (component in DISTRIBUTION) {
64 | val siblingX = x + component.deltaX
65 | val siblingY = y + component.deltaY
66 | if (siblingX in 0 until width && siblingY in 0 until height) {
67 | val offset = error * component.power
68 | colors[siblingY][siblingX] = colors[siblingY][siblingX] + offset
69 | }
70 | }
71 | }
72 | }
73 |
74 | val new = IntArray(bitmap.width * bitmap.height)
75 |
76 | for ((y, lines) in colors.withIndex()) {
77 | for ((x, cell) in lines.withIndex()) {
78 | // XXX Alpha
79 | new[y * width + x] = if (bitmap.getAlphaf(x, y) < 0.5F) {
80 | Int.MIN_VALUE
81 | } else {
82 | var rgb = cell.red shl 8
83 | rgb = (rgb or cell.green) shl 8
84 | rgb = (rgb or cell.blue)
85 | rgb
86 | }
87 | }
88 | }
89 |
90 | return new
91 | }
92 | }
--------------------------------------------------------------------------------
/src/main/kotlin/xyz/cssxsh/skia/gif/ColorTable.kt:
--------------------------------------------------------------------------------
1 | package xyz.cssxsh.skia.gif
2 |
3 | import java.nio.*
4 |
5 | /**
6 | * 调色板
7 | * @param colors 颜色
8 | * @param sort 是否已排序
9 | * @param transparency 透明颜色序号
10 | * @param background 背景颜色序号
11 | */
12 | public class ColorTable(
13 | public val colors: IntArray,
14 | public val sort: Boolean,
15 | public val transparency: Int? = (colors.capacity() - 1).coerceAtLeast(0),
16 | public val background: Int = 0
17 | ) {
18 | public companion object {
19 | private val SizeList = listOf(0, 2, 4, 8, 16, 32, 64, 128, 256)
20 | private fun IntArray.capacity() = SizeList.firstOrNull { it >= size } ?: -1
21 | public val Empty: ColorTable = ColorTable(IntArray(0), false)
22 | }
23 |
24 | init {
25 | check(colors.capacity() != -1) { "Color Table Too Large" }
26 | }
27 |
28 | /**
29 | * 写入
30 | * @param buffer 写入的目标
31 | */
32 | public fun write(buffer: ByteBuffer) {
33 | for (color in colors) {
34 | buffer.put(color.asRGBBytes())
35 | }
36 | buffer.put(ByteArray((colors.capacity() - colors.size) * 3))
37 | }
38 |
39 | /**
40 | * 是否存在(颜色不为空)
41 | */
42 | public fun exists(): Boolean = colors.isNotEmpty()
43 |
44 | /**
45 | * GIF 颜色数量位对应值
46 | */
47 | public fun size(): Int = when (colors.size) {
48 | in 129..256 -> 0x07
49 | in 65..128 -> 0x06
50 | in 33..64 -> 0x05
51 | in 17..32 -> 0x04
52 | in 9..16 -> 0x03
53 | in 5..8 -> 0x02
54 | in 3..4 -> 0x01
55 | in 0..2 -> 0x00
56 | else -> throw IllegalArgumentException("Color Table Size: ${colors.size}")
57 | }
58 | }
--------------------------------------------------------------------------------
/src/main/kotlin/xyz/cssxsh/skia/gif/GIFBuilder.kt:
--------------------------------------------------------------------------------
1 | package xyz.cssxsh.skia.gif
2 |
3 | import org.jetbrains.skia.*
4 | import org.jetbrains.skia.impl.*
5 | import java.nio.*
6 |
7 | /**
8 | * GIF 构建器
9 | * @param width 宽
10 | * @param height 高
11 | */
12 | public class GIFBuilder(public val width: Int, public val height: Int) {
13 | public companion object {
14 | internal const val GIF_HEADER = "GIF89a"
15 | internal const val GIF_TRAILER = ";"
16 | }
17 |
18 | private fun header(buffer: ByteBuffer) = buffer.put(GIF_HEADER.toByteArray(Charsets.US_ASCII))
19 |
20 | private fun trailer(buffer: ByteBuffer) = buffer.put(GIF_TRAILER.toByteArray(Charsets.US_ASCII))
21 |
22 | /**
23 | * [ByteBuffer.capacity]
24 | */
25 | @GIFDsl
26 | public var capacity: Int = 1 shl 23
27 |
28 | /**
29 | * [ByteBuffer.capacity]
30 | */
31 | @GIFDsl
32 | public fun capacity(total: Int): GIFBuilder = apply { capacity = total }
33 |
34 | /**
35 | * Netscape Looping Application Extension, 0 is infinite times
36 | * @see [ApplicationExtension.loop]
37 | */
38 | @GIFDsl
39 | public var loop: Int = 0
40 |
41 | /**
42 | * Netscape Looping Application Extension, 0 is infinite times
43 | * @see [ApplicationExtension.loop]
44 | */
45 | @GIFDsl
46 | public fun loop(count: Int): GIFBuilder = apply { loop = count }
47 |
48 | /**
49 | * Netscape Buffering Application Extension
50 | * @see [ApplicationExtension.buffering]
51 | */
52 | @GIFDsl
53 | public var buffering: Int = 0
54 |
55 | /**
56 | * Netscape Buffering Application Extension
57 | * @see [ApplicationExtension.buffering]
58 | */
59 | @GIFDsl
60 | public fun buffering(open: Boolean): GIFBuilder = apply { buffering = if (open) 0x0001_0000 else 0x0000_0000 }
61 |
62 | /**
63 | * Pixel Aspect Ratio
64 | * @see [LogicalScreenDescriptor.write]
65 | */
66 | @GIFDsl
67 | public var ratio: Int = 0
68 |
69 | /**
70 | * Pixel Aspect Ratio
71 | * @see [LogicalScreenDescriptor.write]
72 | */
73 | @GIFDsl
74 | public fun ratio(size: Int): GIFBuilder = apply {
75 | ratio = size
76 | }
77 |
78 | /**
79 | * GlobalColorTable
80 | * @see [OctTreeQuantizer.quantize]
81 | */
82 | @GIFDsl
83 | public var global: ColorTable = ColorTable.Empty
84 |
85 | /**
86 | * GlobalColorTable
87 | * @see [OctTreeQuantizer.quantize]
88 | */
89 | @GIFDsl
90 | public fun table(bitmap: Bitmap): GIFBuilder = apply {
91 | global = if (bitmap.computeIsOpaque()) {
92 | ColorTable(OctTreeQuantizer().quantize(bitmap, 256), true, null)
93 | } else {
94 | ColorTable(OctTreeQuantizer().quantize(bitmap, 255), true)
95 | }
96 | }
97 |
98 | /**
99 | * GlobalColorTable
100 | */
101 | @GIFDsl
102 | public fun table(value: ColorTable): GIFBuilder = apply {
103 | global = value
104 | }
105 |
106 | /**
107 | * GlobalFrameOptions
108 | */
109 | @GIFDsl
110 | public var options: AnimationFrameInfo = AnimationFrameInfo(
111 | requiredFrame = -1,
112 | duration = 1000,
113 | // no use
114 | isFullyReceived = false,
115 | alphaType = ColorAlphaType.OPAQUE,
116 | isHasAlphaWithinBounds = false,
117 | disposalMethod = AnimationDisposalMode.UNUSED,
118 | blendMode = BlendMode.CLEAR,
119 | frameRect = IRect.makeXYWH(0, 0, 0, 0)
120 | )
121 |
122 | /**
123 | * GlobalFrameOptions
124 | */
125 | @GIFDsl
126 | public fun options(block: AnimationFrameInfo.() -> Unit): GIFBuilder = apply {
127 | options.apply(block)
128 | }
129 |
130 | /**
131 | * 帧集合
132 | */
133 | @GIFDsl
134 | public var frames: MutableList> = ArrayList()
135 |
136 | /**
137 | * 写入帧
138 | * @param bitmap 源位图
139 | * @param colors 调色板
140 | * @param block 帧信息DSL
141 | */
142 | @GIFDsl
143 | public fun frame(
144 | bitmap: Bitmap,
145 | colors: ColorTable = ColorTable.Empty,
146 | block: AnimationFrameInfo.() -> Unit = {}
147 | ): GIFBuilder = apply {
148 | val rect = IRect.makeXYWH(0, 0, bitmap.width, bitmap.height)
149 | frames.add(Triple(bitmap, colors, options.withFrameRect(rect).withAlphaType(bitmap.alphaType).apply(block)))
150 | }
151 |
152 | /**
153 | * 写入帧
154 | * @param bitmap 源位图
155 | * @param colors 调色板
156 | * @param info 帧信息
157 | */
158 | @GIFDsl
159 | public fun frame(
160 | bitmap: Bitmap,
161 | colors: ColorTable = ColorTable.Empty,
162 | info: AnimationFrameInfo
163 | ): GIFBuilder = apply {
164 | frames.add(Triple(bitmap, colors, info))
165 | }
166 |
167 | /**
168 | * 构建到 buffer
169 | * @param buffer 写入的目标
170 | */
171 | @PublishedApi
172 | internal fun build(buffer: ByteBuffer) {
173 | buffer.order(ByteOrder.LITTLE_ENDIAN)
174 |
175 | header(buffer)
176 | LogicalScreenDescriptor.write(buffer, width, height, global, ratio)
177 | if (loop >= 0) ApplicationExtension.loop(buffer, loop)
178 | if (buffering > 0) ApplicationExtension.buffering(buffer, buffering)
179 | for ((bitmap, colors, info) in frames) {
180 | val table = when {
181 | colors.exists() -> colors
182 | global.exists() -> global
183 | else -> {
184 | if (info.alphaType == ColorAlphaType.OPAQUE || bitmap.computeIsOpaque()) {
185 | ColorTable(OctTreeQuantizer().quantize(bitmap, 256), true, null)
186 | } else {
187 | ColorTable(OctTreeQuantizer().quantize(bitmap, 255), true)
188 | }
189 | }
190 | }
191 |
192 | GraphicControlExtension.write(buffer, info.disposalMethod, false, table.transparency, info.duration)
193 |
194 | val result = AtkinsonDitherer.dither(bitmap, table.colors)
195 |
196 | @Suppress("INVISIBLE_REFERENCE", "INVISIBLE_MEMBER")
197 | ImageDescriptor.write(buffer, info.frameRect, table, table !== global, result)
198 | }
199 | trailer(buffer)
200 | }
201 |
202 | /**
203 | * 构建为数据
204 | */
205 | public fun data(): Data {
206 | val data = Data.makeUninitialized(capacity)
207 | val buffer = BufferUtil.getByteBufferFromPointer(data.writableData(), capacity)
208 | build(buffer = buffer)
209 |
210 | return data.makeSubset(0, buffer.position())
211 | }
212 |
213 | /**
214 | * 构建为 bytes
215 | */
216 | public fun build(): ByteArray {
217 | val buffer = ByteBuffer.allocate(capacity)
218 | build(buffer = buffer)
219 |
220 | return buffer.array().sliceArray(0 until buffer.position())
221 | }
222 | }
--------------------------------------------------------------------------------
/src/main/kotlin/xyz/cssxsh/skia/gif/GIFDsl.kt:
--------------------------------------------------------------------------------
1 | package xyz.cssxsh.skia.gif
2 |
3 | import org.jetbrains.skia.*
4 |
5 | internal fun Int.asUnsignedShort(): Short {
6 | check(this in 0..0xFFFF) { toString(16) }
7 | return toShort()
8 | }
9 |
10 | internal fun Int.asUnsignedByte(): Byte {
11 | check(this in 0..0xFF) { toString(16) }
12 | return toByte()
13 | }
14 |
15 | internal fun Int.asRGBBytes(): ByteArray {
16 | return byteArrayOf(
17 | (this and 0xFF0000 shr 16).toByte(),
18 | (this and 0x00FF00 shr 8).toByte(),
19 | (this and 0x0000FF).toByte()
20 | )
21 | }
22 |
23 | /**
24 | * 标记一些函数用于 GIF DSL
25 | */
26 | @DslMarker
27 | public annotation class GIFDsl
28 |
29 | /**
30 | * GIF DSL
31 | */
32 | @GIFDsl
33 | public fun gif(width: Int, height: Int, block: GIFBuilder.() -> Unit): Data {
34 | return GIFBuilder(width, height)
35 | .apply(block)
36 | .data()
37 | }
--------------------------------------------------------------------------------
/src/main/kotlin/xyz/cssxsh/skia/gif/GraphicControlExtension.kt:
--------------------------------------------------------------------------------
1 | package xyz.cssxsh.skia.gif
2 |
3 | import org.jetbrains.skia.*
4 | import java.nio.*
5 |
6 | /**
7 | * GIF Graphic Control Extension Info 写入器
8 | */
9 | public object GraphicControlExtension {
10 | private const val INTRODUCER = 0x21
11 | private const val LABEL = 0xF9
12 | private const val BLOCK_SIZE = 0x04
13 | private const val TERMINATOR = 0x00
14 |
15 | private fun block(
16 | buffer: ByteBuffer,
17 | flags: Byte,
18 | delay: Short,
19 | transparencyIndex: Byte,
20 | ) {
21 | buffer.put(INTRODUCER.asUnsignedByte())
22 | buffer.put(LABEL.asUnsignedByte())
23 | buffer.put(BLOCK_SIZE.asUnsignedByte())
24 | buffer.put(flags)
25 | buffer.putShort(delay)
26 | buffer.put(transparencyIndex)
27 | buffer.put(TERMINATOR.asUnsignedByte())
28 | }
29 |
30 | /**
31 | * 写入
32 | * @param buffer 写入的目标
33 | * @param disposalMethod 切换方法
34 | * @param userInput 用户输入
35 | * @param transparencyIndex 透明位index
36 | * @param millisecond 延迟
37 | */
38 | public fun write(
39 | buffer: ByteBuffer,
40 | disposalMethod: AnimationDisposalMode,
41 | userInput: Boolean,
42 | transparencyIndex: Int?,
43 | millisecond: Int
44 | ) {
45 | // Not Interlaced Images
46 | var flags = 0x0000
47 |
48 | flags = flags or when (disposalMethod) {
49 | AnimationDisposalMode.UNUSED -> 0x00
50 | AnimationDisposalMode.KEEP -> 0x04
51 | AnimationDisposalMode.RESTORE_BG_COLOR -> 0x08
52 | AnimationDisposalMode.RESTORE_PREVIOUS -> 0x0C
53 | }
54 | if (userInput) flags = flags or 0x02
55 | if (transparencyIndex in 0..0xFF) flags = flags or 0x01
56 |
57 | block(
58 | buffer = buffer,
59 | flags = flags.asUnsignedByte(),
60 | delay = (millisecond / 10).asUnsignedShort(),
61 | transparencyIndex = (transparencyIndex ?: 0).asUnsignedByte()
62 | )
63 | }
64 | }
--------------------------------------------------------------------------------
/src/main/kotlin/xyz/cssxsh/skia/gif/ImageDescriptor.kt:
--------------------------------------------------------------------------------
1 | package xyz.cssxsh.skia.gif
2 |
3 | import org.jetbrains.skia.*
4 | import java.nio.*
5 |
6 | /**
7 | * GIF Image Descriptor 写入器
8 | */
9 | public object ImageDescriptor {
10 | private const val SEPARATOR = 0x002C
11 | private const val TERMINATOR = 0x0000
12 |
13 | private fun block(
14 | buffer: ByteBuffer,
15 | left: Short,
16 | top: Short,
17 | width: Short,
18 | height: Short,
19 | flags: Byte,
20 | ) {
21 | buffer.put(SEPARATOR.asUnsignedByte())
22 | buffer.putShort(left)
23 | buffer.putShort(top)
24 | buffer.putShort(width)
25 | buffer.putShort(height)
26 | buffer.put(flags)
27 | }
28 |
29 | private fun data(
30 | buffer: ByteBuffer,
31 | min: Int,
32 | data: ByteArray
33 | ) {
34 | buffer.put(min.asUnsignedByte())
35 | for (index in data.indices step 255) {
36 | val size = minOf(data.size - index, 255)
37 | buffer.put(size.asUnsignedByte())
38 | buffer.put(data, index, size)
39 | }
40 | }
41 |
42 | /**
43 | * 帧数据写入
44 | * @param buffer 写入的目标
45 | * @param rect 显示的位置
46 | * @param table 调色板
47 | * @param local 为当前帧写入调色板
48 | * @param image 像素数据
49 | */
50 | public fun write(buffer: ByteBuffer, rect: IRect, table: ColorTable, local: Boolean, image: IntArray) {
51 | // Not Interlaced Images
52 | var flags = 0x00
53 |
54 | if (local) {
55 | flags = 0x80 or table.size()
56 | if (table.sort) {
57 | flags = flags or 0x10
58 | }
59 | }
60 |
61 | block(
62 | buffer = buffer,
63 | left = rect.left.asUnsignedShort(),
64 | top = rect.top.asUnsignedShort(),
65 | width = rect.width.asUnsignedShort(),
66 | height = rect.height.asUnsignedShort(),
67 | flags = flags.asUnsignedByte()
68 | )
69 |
70 | if (local) table.write(buffer)
71 |
72 | val (min, lzw) = LZWEncoder(table, image).encode()
73 |
74 | data(buffer, min, lzw)
75 |
76 | buffer.put(TERMINATOR.asUnsignedByte())
77 | }
78 | }
--------------------------------------------------------------------------------
/src/main/kotlin/xyz/cssxsh/skia/gif/LZWEncoder.kt:
--------------------------------------------------------------------------------
1 | package xyz.cssxsh.skia.gif
2 |
3 | import java.util.*
4 |
5 | /**
6 | * LZW 编码器
7 | * @param colors 调色板
8 | * @param image 颜色数据
9 | */
10 | public class LZWEncoder(private val colors: ColorTable, private val image: IntArray) {
11 | internal companion object {
12 | val CLEAR_CODE = listOf(-1)
13 | val END_OF_INFO = listOf(-2)
14 |
15 | const val MAX_CODE_TABLE_SIZE = 1 shl 12
16 | }
17 |
18 | private val minimumCodeSize = colors.size() + 1
19 | private val outputBits = BitSet()
20 | private var position = 0
21 | private val table: MutableMap, Int> = HashMap()
22 | private var codeSize = 0
23 | private var indexBuffer: List = emptyList()
24 |
25 | init {
26 | resetCodeTableAndCodeSize()
27 | }
28 |
29 | /**
30 | * 编码
31 | * @return 大小和压缩数据
32 | */
33 | public fun encode(): Pair {
34 | writeCode(table.getValue(CLEAR_CODE))
35 | for (rgb in image) {
36 | val index = colors.colors.indexOf(rgb)
37 | processIndex(if (index != -1) index else colors.transparency ?: colors.background)
38 | }
39 | writeCode(table.getValue(indexBuffer))
40 | writeCode(table.getValue(END_OF_INFO))
41 | return minimumCodeSize to toBytes()
42 | }
43 |
44 | private fun processIndex(index: Int) {
45 | val extendedIndexBuffer = indexBuffer + index
46 | indexBuffer = if (extendedIndexBuffer in table) {
47 | extendedIndexBuffer
48 | } else {
49 | writeCode(table.getValue(indexBuffer))
50 | if (table.size == MAX_CODE_TABLE_SIZE) {
51 | writeCode(table.getValue(CLEAR_CODE))
52 | resetCodeTableAndCodeSize()
53 | } else {
54 | addCodeToTable(extendedIndexBuffer)
55 | }
56 | listOf(index)
57 | }
58 | }
59 |
60 | private fun writeCode(code: Int) {
61 | for (shift in 0 until codeSize) {
62 | val bit = code ushr shift and 1 != 0
63 | outputBits.set(position++, bit)
64 | }
65 | }
66 |
67 | private fun toBytes(): ByteArray {
68 | val bitCount: Int = position
69 | val result = ByteArray((bitCount + 7) / 8)
70 | for (i in 0 until bitCount) {
71 | val byteIndex = i / 8
72 | val bitIndex = i % 8
73 | result[byteIndex] = ((if (outputBits.get(i)) 1 else 0) shl bitIndex or result[byteIndex].toInt()).toByte()
74 | }
75 | return result
76 | }
77 |
78 | private fun addCodeToTable(indices: List) {
79 | val newCode: Int = table.size
80 | table[indices] = newCode
81 | if (newCode == 1 shl codeSize) {
82 | ++codeSize
83 | }
84 | }
85 |
86 | private fun resetCodeTableAndCodeSize() {
87 | table.clear()
88 |
89 | val colorsInCodeTable = 1 shl minimumCodeSize
90 | for (i in 0 until colorsInCodeTable) {
91 | table[listOf(i)] = i
92 | }
93 | table[CLEAR_CODE] = table.size
94 | table[END_OF_INFO] = table.size
95 |
96 | codeSize = minimumCodeSize + 1
97 | }
98 | }
--------------------------------------------------------------------------------
/src/main/kotlin/xyz/cssxsh/skia/gif/LogicalScreenDescriptor.kt:
--------------------------------------------------------------------------------
1 | package xyz.cssxsh.skia.gif
2 |
3 | import java.nio.*
4 |
5 | /**
6 | * GIF Logical ScreenDescriptor 写入器
7 | */
8 | public object LogicalScreenDescriptor {
9 |
10 | private fun block(
11 | buffer: ByteBuffer,
12 | width: Short,
13 | height: Short,
14 | flags: Byte,
15 | backgroundColorIndex: Byte,
16 | pixelAspectRatio: Byte
17 | ) {
18 | buffer.putShort(width)
19 | buffer.putShort(height)
20 | buffer.put(flags)
21 | buffer.put(backgroundColorIndex)
22 | buffer.put(pixelAspectRatio)
23 | }
24 |
25 | /**
26 | * 帧数据写入
27 | * @param buffer 写入的目标
28 | * @param width 宽
29 | * @param height 高
30 | * @param table 调色板
31 | * @param ratio 像素宽高比
32 | */
33 | public fun write(
34 | buffer: ByteBuffer,
35 | width: Int,
36 | height: Int,
37 | table: ColorTable,
38 | ratio: Int
39 | ) {
40 | // Color Resolution Use 7
41 | var flags = 0x70
42 |
43 | if (table.exists()) {
44 | flags = flags or 0x80 or table.size()
45 | }
46 |
47 | if (table.sort) {
48 | flags = flags or 0x08
49 | }
50 |
51 | block(
52 | buffer = buffer,
53 | width = width.asUnsignedShort(),
54 | height = height.asUnsignedShort(),
55 | flags = flags.asUnsignedByte(),
56 | backgroundColorIndex = table.background.asUnsignedByte(),
57 | pixelAspectRatio = ratio.asUnsignedByte()
58 | )
59 |
60 | table.write(buffer)
61 | }
62 | }
--------------------------------------------------------------------------------
/src/main/kotlin/xyz/cssxsh/skia/gif/OctTreeQuantizer.kt:
--------------------------------------------------------------------------------
1 | package xyz.cssxsh.skia.gif
2 |
3 | import org.jetbrains.skia.*
4 |
5 | /**
6 | * Implements qct-tree quantization.
7 | *
8 | *
9 | * The principle of algorithm: [http://www.microsoft.com/msj/archive/S3F1.aspx]
10 | *
11 | */
12 | public class OctTreeQuantizer {
13 | private val mask = intArrayOf(0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01)
14 |
15 | private var leafCount = 0
16 | private var inIndex = 0
17 | private val nodeList = arrayOfNulls(8)
18 |
19 | /**
20 | * 量化处理
21 | * @param bitmap 位图数据
22 | * @param maxColorCount 最大颜色数量
23 | * @return RGB调色板
24 | */
25 | public fun quantize(bitmap: Bitmap, maxColorCount: Int = 256): IntArray {
26 | val node = createNode(0)
27 | for (x in 0 until bitmap.width) {
28 | for (y in 0 until bitmap.height) {
29 | val color = bitmap.getColor(x, y)
30 | addColor(node, color, 0)
31 | while (leafCount > maxColorCount) {
32 | reduceTree()
33 | }
34 | }
35 | }
36 | val colors: MutableSet = HashSet()
37 | getColorPalette(node, colors)
38 | leafCount = 0
39 | inIndex = 0
40 | for (i in 0..7) {
41 | nodeList[i] = null
42 | }
43 | return colors.toIntArray()
44 | }
45 |
46 | private fun addColor(node_: Node?, color: Int, inLevel: Int): Boolean {
47 | val node = node_ ?: createNode(inLevel)
48 | val nIndex: Int
49 | val shift: Int
50 | val red = (color shr 16) and 0xFF
51 | val green = (color shr 8) and 0xFF
52 | val blue = color and 0xFF
53 | if (node.isLeaf) {
54 | node.pixelCount++
55 | node.redSum += red
56 | node.greenSum += green
57 | node.blueSum += blue
58 | } else {
59 | shift = 7 - inLevel
60 | nIndex = (red and mask[inLevel] shr shift shl 2
61 | or (green and mask[inLevel] shr shift shl 1)
62 | or (blue and mask[inLevel] shr shift))
63 | var tmpNode = node.child[nIndex]
64 | if (tmpNode == null) {
65 | tmpNode = createNode(inLevel + 1)
66 | }
67 | node.child[nIndex] = tmpNode
68 | return addColor(node.child[nIndex], color, inLevel + 1)
69 | }
70 | return true
71 | }
72 |
73 | private fun createNode(level: Int): Node {
74 | val node = Node()
75 | node.level = level
76 | node.isLeaf = level == 8
77 | if (node.isLeaf) {
78 | leafCount++
79 | } else {
80 | node.next = nodeList[level]
81 | nodeList[level] = node
82 | }
83 | return node
84 | }
85 |
86 | private fun reduceTree() {
87 | var redSum = 0
88 | var greenSum = 0
89 | var blueSum = 0
90 | var count = 0
91 | var i = 7
92 | while (i > 0) {
93 | if (nodeList[i] != null) break
94 | i--
95 | }
96 | val tmpNode = nodeList[i]
97 | nodeList[i] = tmpNode!!.next
98 | i = 0
99 | while (i < 8) {
100 | if (tmpNode.child[i] != null) {
101 | redSum += tmpNode.child[i]!!.redSum
102 | greenSum += tmpNode.child[i]!!.greenSum
103 | blueSum += tmpNode.child[i]!!.blueSum
104 | count += tmpNode.child[i]!!.pixelCount
105 | tmpNode.child[i] = null
106 | leafCount--
107 | }
108 | i++
109 | }
110 | tmpNode.isLeaf = true
111 | tmpNode.redSum = redSum
112 | tmpNode.greenSum = greenSum
113 | tmpNode.blueSum = blueSum
114 | tmpNode.pixelCount = count
115 | leafCount++
116 | }
117 |
118 | private fun getColorPalette(node: Node?, colors: MutableSet) {
119 | if (node!!.isLeaf) {
120 | node.colorIndex = inIndex
121 | node.redSum = node.redSum / node.pixelCount
122 | node.greenSum = node.greenSum / node.pixelCount
123 | node.blueSum = node.blueSum / node.pixelCount
124 | node.pixelCount = 1
125 | inIndex++
126 | val red = node.redSum and 0xFF
127 | val green = node.greenSum and 0xFF
128 | val blue = node.blueSum and 0xFF
129 | colors.add((red shl 16) or (green shl 8) or (blue shr 0))
130 | } else {
131 | for (i in 0..7) {
132 | if (node.child[i] != null) {
133 | getColorPalette(node.child[i], colors)
134 | }
135 | }
136 | }
137 | }
138 |
139 | private class Node {
140 | var isLeaf = false
141 | var level = 0
142 | var colorIndex = 0
143 | var redSum = 0
144 | var greenSum = 0
145 | var blueSum = 0
146 | var pixelCount = 0
147 | var child = arrayOfNulls(8)
148 | var next: Node? = null
149 | }
150 | }
--------------------------------------------------------------------------------
/src/main/resources/META-INF/services/net.mamoe.mirai.console.plugin.jvm.JvmPlugin:
--------------------------------------------------------------------------------
1 | xyz.cssxsh.mirai.skia.MiraiSkiaPlugin
--------------------------------------------------------------------------------
/src/test/kotlin/xyz/cssxsh/gif/EncoderTest.kt:
--------------------------------------------------------------------------------
1 | package xyz.cssxsh.gif
2 |
3 | import kotlinx.coroutines.*
4 | import org.jetbrains.skia.*
5 | import org.junit.jupiter.api.*
6 | import xyz.cssxsh.mirai.skia.*
7 | import xyz.cssxsh.skia.*
8 | import java.io.File
9 |
10 | internal class EncoderTest {
11 | init {
12 | runBlocking {
13 | System.setProperty("xyz.cssxsh.mirai.gif.release", "https://github.com/cssxsh/gif-jni/releases/download")
14 | loadJNILibrary(folder = File("./run/lib"))
15 | }
16 | }
17 |
18 | @Test
19 | fun build() {
20 | val face = Image.makeFromEncoded(File("./example/face.png").readBytes())
21 | val sprite = Image.makeFromEncoded(File("./example/sprite.png").readBytes())
22 | val surface = Surface.makeRasterN32Premul(112 * 5, 112)
23 | val rects = listOf(
24 | // 0, 0, 0, 0
25 | Rect.makeXYWH(21F, 21F, 91F, 91F),
26 | // -4, 12, 4, -12
27 | Rect.makeXYWH(112F + 21F - 4F, 21F + 12F, 91F + 4F, 91F - 12F),
28 | // -12, 18, 12, -18
29 | Rect.makeXYWH(224F + 21F - 12F, 21F + 18F, 91F + 12F, 91F - 18F),
30 | // -8, 12, 4, -12
31 | Rect.makeXYWH(336F + 21F - 8F, 21F + 12F, 91F + 4F, 91F - 12F),
32 | // -4, 0, 0, 0
33 | Rect.makeXYWH(448F + 21F - 4F, 21F, 91F, 91F)
34 | )
35 |
36 | for (rect in rects) surface.canvas.drawImageRect(face, rect)
37 |
38 | surface.canvas.drawImage(sprite, 0F, 0F)
39 |
40 | val gif = File("./run/jni.gif")
41 | gif.parentFile.mkdirs()
42 |
43 | Encoder(gif, 112, 112).use { encoder ->
44 | encoder.repeat = -1
45 |
46 | repeat(5) { index ->
47 | val rect = IRect.makeXYWH(112 * index, 0, 112, 112)
48 | val image = requireNotNull(surface.makeImageSnapshot(rect)) { "Make image snapshot fail" }
49 |
50 | encoder.writeImage(image, 20, AnimationDisposalMode.RESTORE_BG_COLOR)
51 | }
52 | }
53 | }
54 |
55 | @Test
56 | fun dear() {
57 | val face = Image.makeFromEncoded(File("./example/face.png").readBytes())
58 | System.setProperty(DEAR_ORIGIN, "./example/dear.gif")
59 | val dst = File("./run/dear.gif")
60 | dst.delete()
61 | dear(face).renameTo(dst)
62 | }
63 | }
--------------------------------------------------------------------------------
/src/test/kotlin/xyz/cssxsh/skia/ExampleKtTest.kt:
--------------------------------------------------------------------------------
1 | package xyz.cssxsh.skia
2 |
3 | import io.ktor.utils.io.core.*
4 | import kotlinx.coroutines.*
5 | import org.jetbrains.skia.*
6 | import org.jetbrains.skia.paragraph.*
7 | import org.jetbrains.skia.svg.*
8 | import org.jetbrains.skiko.*
9 | import org.junit.jupiter.api.*
10 | import xyz.cssxsh.mirai.skia.*
11 | import java.io.*
12 |
13 | @TestInstance(TestInstance.Lifecycle.PER_CLASS)
14 | internal class ExampleKtTest {
15 |
16 | private val fonts = File("./run/fonts")
17 |
18 | @BeforeAll
19 | fun init() {
20 | fonts.mkdirs()
21 | System.setProperty("xyz.cssxsh.mirai.gif.release", "https://github.com/cssxsh/gif-jni")
22 | val links = arrayOf(
23 | "https://raw.githubusercontent.com/dcalsky/bbq/master/fonts/FZXS14-ex.ttf",
24 | "https://forum.freemdict.com/uploads/short-url/57rcFi1dOBZBbcQu6762Y776rVD.ttf",
25 | "https://cdn.cnbj1.fds.api.mi-img.com/vipmlmodel/font/MiSans/MiSans.zip",
26 | "https://github.com/googlefonts/noto-emoji/archive/refs/tags/v2.038.tar.gz",
27 | "https://github.com/be5invis/Sarasa-Gothic/releases/download/v0.37.4/sarasa-gothic-ttf-0.37.4.7z"
28 | )
29 | runBlocking {
30 | loadJNILibrary(folder = File("./run/lib"))
31 | if (fonts.list().isNullOrEmpty()) downloadTypeface(folder = fonts, links = links)
32 | }
33 | }
34 |
35 | @Test
36 | fun font() {
37 | println(FontUtils.families())
38 |
39 | when (hostOs) {
40 | OS.Windows -> {
41 | Assertions.assertNotNull(FontUtils.matchSimSun(FontStyle.NORMAL))
42 | Assertions.assertNotNull(FontUtils.matchNSimSun(FontStyle.NORMAL))
43 | // Assertions.assertNotNull(FontUtils.matchSimHei(FontStyle.NORMAL))
44 | // Assertions.assertNotNull(FontUtils.matchFangSong(FontStyle.NORMAL))
45 | // Assertions.assertNotNull(FontUtils.matchKaiTi(FontStyle.NORMAL))
46 | Assertions.assertNotNull(FontUtils.matchArial(FontStyle.NORMAL))
47 | Assertions.assertNotNull(FontUtils.matchCalibri(FontStyle.NORMAL))
48 | Assertions.assertNotNull(FontUtils.matchConsolas(FontStyle.NORMAL))
49 | Assertions.assertNotNull(FontUtils.matchTimesNewRoman(FontStyle.NORMAL))
50 | }
51 | OS.Linux -> {
52 | Assertions.assertNotNull(FontUtils.matchLiberationSans(FontStyle.NORMAL))
53 | Assertions.assertNotNull(FontUtils.matchLiberationSerif(FontStyle.NORMAL))
54 | }
55 | OS.MacOS -> {
56 | Assertions.assertNotNull(FontUtils.matchArial(FontStyle.NORMAL))
57 | Assertions.assertNotNull(FontUtils.matchTimesNewRoman(FontStyle.NORMAL))
58 | Assertions.assertNotNull(FontUtils.matchHelvetica(FontStyle.NORMAL))
59 | }
60 | else -> Unit
61 | }
62 |
63 | loadTypeface(folder = fonts)
64 | println(FontUtils.provider.makeFamilies())
65 | }
66 |
67 | @Test
68 | fun svg() {
69 | val surface = Surface.makeRasterN32Premul(350, 350)
70 | val size = Point(350F, 350F)
71 | val background = SVGDOM.makeFromFile(xml = File("./example/osu-logo-triangles.svg"))
72 | background.setContainerSize(size)
73 | background.render(surface.canvas)
74 | val text = SVGDOM.makeFromFile(xml = File("./example/osu-logo-white.svg"))
75 | text.setContainerSize(size)
76 | text.render(surface.canvas)
77 |
78 | val image = surface.makeImageSnapshot()
79 | val data = image.encodeToData() ?: throw IllegalStateException("encode null.")
80 |
81 | val file = File("./run/Osu.png")
82 | file.writeBytes(data.bytes)
83 | }
84 |
85 | @Test
86 | fun stats() {
87 | val stats = SVGDOM.makeFromFile(xml = File("./example/cssxsh.svg"))
88 | val surface = Surface.makeRasterN32Premul(stats.root!!.width.value.toInt(), stats.root!!.height.value.toInt())
89 |
90 | stats.setContainerSize(stats.root!!.width.value, stats.root!!.height.value)
91 | stats.render(surface.canvas)
92 |
93 | val image = surface.makeImageSnapshot()
94 | val data = image.encodeToData() ?: throw IllegalStateException("encode null.")
95 |
96 | val file = File("./run/cssxsh.png")
97 | file.writeBytes(data.bytes)
98 | }
99 |
100 | @Test
101 | fun pornhub() {
102 | val surface = pornhub("Git", "Hub")
103 |
104 | val image = surface.makeImageSnapshot()
105 | val data = image.encodeToData() ?: throw IllegalStateException("encode null.")
106 |
107 | val file = File("./run/pornhub.png")
108 | file.writeBytes(data.bytes)
109 | }
110 |
111 | @Test
112 | fun petpet() {
113 | System.setProperty(PET_PET_SPRITE, "./example/sprite.png")
114 | val data = petpet(face = Image.makeFromEncoded(File("./example/face.png").readBytes()))
115 |
116 | val file = File("./run/petpet.gif")
117 | file.writeBytes(data.bytes)
118 | }
119 |
120 | @Test
121 | fun choyen() {
122 | val surface = choyen(top = "好了", bottom = "够意思")
123 |
124 | val image = surface.makeImageSnapshot()
125 | val data = image.encodeToData() ?: throw IllegalStateException("encode null.")
126 |
127 | val file = File("./run/choyen.png")
128 | file.writeBytes(data.bytes)
129 | }
130 |
131 | @Test
132 | fun zzkia() {
133 | System.setProperty(ZZKIA_ORIGIN, "./example/zzkia.jpg")
134 | val surface = zzkia("有内鬼,停止交易")
135 |
136 | val image = surface.makeImageSnapshot()
137 | val data = image.encodeToData() ?: throw IllegalStateException("encode null.")
138 |
139 | val file = File("./run/zzkia.png")
140 | file.writeBytes(data.bytes)
141 | }
142 |
143 | @Test
144 | fun tank() {
145 | val top = Image.makeFromEncoded(File("./example/90446978_p0.png").readBytes())
146 | val bottom = Image.makeFromEncoded(File("./example/90487779_p0.png").readBytes())
147 | val surface = tank(top = top, bottom = bottom)
148 |
149 | val image = surface.makeImageSnapshot()
150 | val data = image.encodeToData() ?: throw IllegalStateException("encode null.")
151 |
152 | val file = File("./run/tank.png")
153 | file.writeBytes(data.bytes)
154 | }
155 |
156 | @Test
157 | fun `utf-16`() {
158 | val test = "天网开发组"
159 |
160 | val surface = Surface.makeRasterN32Premul(600, 300)
161 | val fonts = FontCollection()
162 | .setDynamicFontManager(FontUtils.provider)
163 | .setDefaultFontManager(FontMgr.default, "FZXS14")
164 | val default = ParagraphStyle()
165 | val paragraph = ParagraphBuilder(default, fonts)
166 | val bytes = test.toByteArray(Charsets.UTF_32)
167 | for (index in bytes.indices step 4) {
168 | val a = bytes[index + 0].toInt() and 0xFF
169 | val r = bytes[index + 1].toInt() and 0xFF
170 | val g = bytes[index + 2].toInt() and 0xFF
171 | val b = bytes[index + 3].toInt() and 0xFF
172 |
173 | val color = Color.makeARGB(
174 | a = a or r or b or g,
175 | r = if (r == 0) g xor b else r xor 0xFF,
176 | g = g xor 0xFF,
177 | b = b xor 0xFF,
178 | )
179 | println("${test[index / 4]} ${color.toUInt().toString(16)}")
180 | val style = TextStyle()
181 | .setFontSize(100F)
182 | .setColor(color)
183 | paragraph
184 | .pushStyle(style)
185 | .addText(test[index / 4].toString())
186 | }
187 |
188 | paragraph.build()
189 | .layout(500F)
190 | .paint(surface.canvas, 50F, 50F)
191 |
192 | val image = surface.makeImageSnapshot()
193 | val data = image.encodeToData() ?: throw IllegalStateException("encode null.")
194 |
195 | val file = File("./run/UTF-16.png")
196 | file.writeBytes(data.bytes)
197 | }
198 | }
--------------------------------------------------------------------------------
/src/test/kotlin/xyz/cssxsh/skia/StyleUtilsTest.kt:
--------------------------------------------------------------------------------
1 | package xyz.cssxsh.skia
2 |
3 | import kotlinx.coroutines.*
4 | import org.jetbrains.skia.*
5 | import org.junit.jupiter.api.*
6 | import xyz.cssxsh.mirai.skia.*
7 | import java.io.File
8 | import kotlin.random.Random
9 |
10 | internal class StyleUtilsTest {
11 |
12 | init {
13 | runBlocking {
14 | System.setProperty("xyz.cssxsh.mirai.gif.release", "https://github.com/cssxsh/gif-jni")
15 | loadJNILibrary(folder = File("./run/lib"))
16 | }
17 | }
18 |
19 | @Test
20 | fun generateLowPoly() {
21 | val file = File("./example/style.test.jpg")
22 | val image = Image.makeFromEncoded(file.readBytes())
23 | val bitmap = Bitmap.makeFromImage(image)
24 | val r = bitmap.generateLowPoly(0.30, 150, 20, 10, Random.nextInt())
25 | println(r.imageInfo)
26 | File("./run/render.png").writeBytes(Image.makeFromBitmap(r).encodeToData()!!.bytes)
27 | }
28 | }
--------------------------------------------------------------------------------
/src/test/resources/META-INF/services/org.slf4j.spi.SLF4JServiceProvider:
--------------------------------------------------------------------------------
1 | org.slf4j.simple.SimpleServiceProvider
--------------------------------------------------------------------------------