├── sample ├── .gitignore ├── src │ └── main │ │ ├── res │ │ ├── values │ │ │ ├── strings.xml │ │ │ ├── styles.xml │ │ │ └── dimens.xml │ │ ├── mipmap-hdpi │ │ │ └── ic_launcher.png │ │ ├── mipmap-mdpi │ │ │ └── ic_launcher.png │ │ ├── mipmap-xhdpi │ │ │ └── ic_launcher.png │ │ ├── mipmap-xxhdpi │ │ │ └── ic_launcher.png │ │ ├── values-w820dp │ │ │ └── dimens.xml │ │ └── layout │ │ │ └── activity_main.xml │ │ ├── svg │ │ ├── ic_smartphone.svg │ │ └── ic_laptop.svg │ │ ├── AndroidManifest.xml │ │ └── java │ │ └── com │ │ └── trello │ │ └── victorsample │ │ └── MainActivity.java ├── build.gradle └── build.gradle.kts.example ├── .idea ├── .gitignore ├── compiler.xml ├── runConfigurations.xml ├── misc.xml ├── jarRepositories.xml └── codeStyles │ └── Project.xml ├── settings.gradle ├── victor ├── src │ ├── test │ │ ├── resources │ │ │ ├── invalid.svg │ │ │ ├── rasterize-expected.png │ │ │ ├── pixel-hdpi-expected.png │ │ │ ├── pixel-ldpi-expected.png │ │ │ ├── pixel-mdpi-expected.png │ │ │ ├── pixel-xhdpi-expected.png │ │ │ ├── relative-hdpi-expected.png │ │ │ ├── relative-ldpi-expected.png │ │ │ ├── relative-mdpi-expected.png │ │ │ ├── relative-xhdpi-expected.png │ │ │ ├── image-tag-rasterize-expected.png │ │ │ ├── problematic-rasterize-expected.png │ │ │ ├── invalid2.svg │ │ │ ├── pixel.svg │ │ │ ├── rasterize.svg │ │ │ ├── relative.svg │ │ │ └── problematic.svg │ │ └── groovy │ │ │ └── com │ │ │ └── trello │ │ │ └── victor │ │ │ ├── SVGResourceTests.groovy │ │ │ └── ConverterTests.groovy │ └── main │ │ ├── groovy │ │ └── com │ │ │ └── trello │ │ │ └── victor │ │ │ ├── Density.groovy │ │ │ ├── VictorPluginExtension.groovy │ │ │ ├── Converter.groovy │ │ │ ├── SVGResource.groovy │ │ │ ├── VictorPlugin.groovy │ │ │ └── RasterizeTask.groovy │ │ └── java │ │ └── org │ │ └── apache │ │ └── batik │ │ └── ext │ │ └── awt │ │ └── image │ │ └── codec │ │ └── imageio │ │ ├── ImageIOPNGImageWriter.java │ │ ├── ImageIOTIFFImageWriter.java │ │ ├── ImageIOPNGRegistryEntry.java │ │ ├── ImageIOJPEGRegistryEntry.java │ │ ├── ImageIOTIFFRegistryEntry.java │ │ ├── ImageIOJPEGImageWriter.java │ │ ├── AbstractImageIORegistryEntry.java │ │ └── ImageIOImageWriter.java └── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── .travis.yml ├── gradle.properties ├── .gitignore ├── CHANGELOG.md ├── gradlew.bat ├── README.md ├── gradlew └── LICENSE /sample/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /.idea/.gitignore: -------------------------------------------------------------------------------- 1 | # Default ignored files 2 | /workspace.xml -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':victor' 2 | include ':sample' 3 | -------------------------------------------------------------------------------- /victor/src/test/resources/invalid.svg: -------------------------------------------------------------------------------- 1 | This is most certainly not a valid SVG file. -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/trello-archive/victor/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /sample/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | Victor Sample 3 | 4 | -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/trello-archive/victor/HEAD/sample/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/trello-archive/victor/HEAD/sample/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/trello-archive/victor/HEAD/sample/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /victor/src/test/resources/rasterize-expected.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/trello-archive/victor/HEAD/victor/src/test/resources/rasterize-expected.png -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/trello-archive/victor/HEAD/sample/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /victor/src/test/resources/pixel-hdpi-expected.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/trello-archive/victor/HEAD/victor/src/test/resources/pixel-hdpi-expected.png -------------------------------------------------------------------------------- /victor/src/test/resources/pixel-ldpi-expected.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/trello-archive/victor/HEAD/victor/src/test/resources/pixel-ldpi-expected.png -------------------------------------------------------------------------------- /victor/src/test/resources/pixel-mdpi-expected.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/trello-archive/victor/HEAD/victor/src/test/resources/pixel-mdpi-expected.png -------------------------------------------------------------------------------- /victor/src/test/resources/pixel-xhdpi-expected.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/trello-archive/victor/HEAD/victor/src/test/resources/pixel-xhdpi-expected.png -------------------------------------------------------------------------------- /victor/src/test/resources/relative-hdpi-expected.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/trello-archive/victor/HEAD/victor/src/test/resources/relative-hdpi-expected.png -------------------------------------------------------------------------------- /victor/src/test/resources/relative-ldpi-expected.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/trello-archive/victor/HEAD/victor/src/test/resources/relative-ldpi-expected.png -------------------------------------------------------------------------------- /victor/src/test/resources/relative-mdpi-expected.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/trello-archive/victor/HEAD/victor/src/test/resources/relative-mdpi-expected.png -------------------------------------------------------------------------------- /victor/src/test/resources/relative-xhdpi-expected.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/trello-archive/victor/HEAD/victor/src/test/resources/relative-xhdpi-expected.png -------------------------------------------------------------------------------- /victor/src/test/resources/image-tag-rasterize-expected.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/trello-archive/victor/HEAD/victor/src/test/resources/image-tag-rasterize-expected.png -------------------------------------------------------------------------------- /victor/src/test/resources/problematic-rasterize-expected.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/trello-archive/victor/HEAD/victor/src/test/resources/problematic-rasterize-expected.png -------------------------------------------------------------------------------- /victor/src/test/resources/invalid2.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /.idea/compiler.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.0.2-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /sample/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /sample/src/main/res/values/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 16dp 4 | 16dp 5 | 6 | -------------------------------------------------------------------------------- /sample/src/main/svg/ic_smartphone.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /sample/src/main/svg/ic_laptop.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /victor/src/test/resources/pixel.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /victor/src/test/resources/rasterize.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /victor/src/test/resources/relative.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /sample/src/main/res/values-w820dp/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 64dp 6 | 7 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: android 2 | 3 | android: 4 | components: 5 | - tools 6 | - platform-tools 7 | - build-tools-30.0.2 8 | - android-30 9 | - extra-android-m2repository 10 | 11 | before_install: 12 | - yes | sdkmanager "platforms;android-30" 13 | 14 | jdk: oraclejdk8 15 | 16 | notifications: 17 | email: false 18 | 19 | sudo: false 20 | 21 | cache: 22 | directories: 23 | - $HOME/.gradle 24 | 25 | script: ./gradlew build test 26 | -------------------------------------------------------------------------------- /.idea/runConfigurations.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 12 | 13 | -------------------------------------------------------------------------------- /sample/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 10 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 9 | 10 | 11 | 12 | 13 | 1.8 14 | 15 | 20 | 21 | 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | 3 | # IDE (e.g. Android Studio) users: 4 | # Gradle settings configured through the IDE *will override* 5 | # any settings specified in this file. 6 | 7 | # For more details on how to configure your build environment visit 8 | # http://www.gradle.org/docs/current/userguide/build_environment.html 9 | 10 | # Specifies the JVM arguments used for the daemon process. 11 | # The setting is particularly useful for tweaking memory settings. 12 | # Default value: -Xmx10248m -XX:MaxPermSize=256m 13 | # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 14 | 15 | # When configured, Gradle will run in incubating parallel mode. 16 | # This option should only be used with decoupled projects. More details, visit 17 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 18 | # org.gradle.parallel=true 19 | 20 | android.useAndroidX=true -------------------------------------------------------------------------------- /victor/src/test/resources/problematic.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /.idea/jarRepositories.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 9 | 10 | 14 | 15 | 19 | 20 | 24 | 25 | -------------------------------------------------------------------------------- /victor/src/main/groovy/com/trello/victor/Density.groovy: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Trello, Inc 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.trello.victor 18 | 19 | /** 20 | * Represents the different densities we can scale assets for. 21 | */ 22 | enum Density { 23 | 24 | LDPI(0.75f), 25 | MDPI(1), 26 | HDPI(1.5f), 27 | XHDPI(2), 28 | XXHDPI(3), 29 | XXXHDPI(4); 30 | 31 | float multiplier; 32 | 33 | Density(float multiplier) { 34 | this.multiplier = multiplier 35 | } 36 | 37 | float getMultiplier() { 38 | return multiplier 39 | } 40 | } -------------------------------------------------------------------------------- /sample/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 14 | 15 | 20 | 21 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /sample/src/main/java/com/trello/victorsample/MainActivity.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Trello, Inc 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.trello.victorsample; 18 | 19 | import android.os.Bundle; 20 | import android.widget.ImageView; 21 | 22 | import androidx.appcompat.app.AppCompatActivity; 23 | 24 | public class MainActivity extends AppCompatActivity { 25 | 26 | @Override 27 | protected void onCreate(Bundle savedInstanceState) { 28 | super.onCreate(savedInstanceState); 29 | setContentView(R.layout.activity_main); 30 | 31 | ImageView secondImageView = (ImageView) findViewById(R.id.second_image_view); 32 | secondImageView.setImageResource(R.drawable.ic_smartphone); 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /victor/src/main/java/org/apache/batik/ext/awt/image/codec/imageio/ImageIOPNGImageWriter.java: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Licensed to the Apache Software Foundation (ASF) under one or more 4 | contributor license agreements. See the NOTICE file distributed with 5 | this work for additional information regarding copyright ownership. 6 | The ASF licenses this file to You under the Apache License, Version 2.0 7 | (the "License"); you may not use this file except in compliance with 8 | the License. You may obtain a copy of the License at 9 | 10 | http://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 | package org.apache.batik.ext.awt.image.codec.imageio; 20 | 21 | /** 22 | * ImageWriter that encodes PNG images using Image I/O. 23 | * 24 | * @version $Id$ 25 | */ 26 | public class ImageIOPNGImageWriter extends ImageIOImageWriter { 27 | 28 | /** 29 | * Main constructor. 30 | */ 31 | public ImageIOPNGImageWriter() { 32 | super("image/png"); 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /victor/src/main/java/org/apache/batik/ext/awt/image/codec/imageio/ImageIOTIFFImageWriter.java: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Licensed to the Apache Software Foundation (ASF) under one or more 4 | contributor license agreements. See the NOTICE file distributed with 5 | this work for additional information regarding copyright ownership. 6 | The ASF licenses this file to You under the Apache License, Version 2.0 7 | (the "License"); you may not use this file except in compliance with 8 | the License. You may obtain a copy of the License at 9 | 10 | http://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 | package org.apache.batik.ext.awt.image.codec.imageio; 20 | 21 | /** 22 | * ImageWriter that encodes TIFF images using Image I/O. 23 | * 24 | * @version $Id$ 25 | */ 26 | public class ImageIOTIFFImageWriter extends ImageIOImageWriter { 27 | 28 | /** 29 | * Main constructor. 30 | */ 31 | public ImageIOTIFFImageWriter() { 32 | super("image/tiff"); 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /victor/src/main/java/org/apache/batik/ext/awt/image/codec/imageio/ImageIOPNGRegistryEntry.java: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Licensed to the Apache Software Foundation (ASF) under one or more 4 | contributor license agreements. See the NOTICE file distributed with 5 | this work for additional information regarding copyright ownership. 6 | The ASF licenses this file to You under the Apache License, Version 2.0 7 | (the "License"); you may not use this file except in compliance with 8 | the License. You may obtain a copy of the License at 9 | 10 | http://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 | package org.apache.batik.ext.awt.image.codec.imageio; 20 | 21 | /** 22 | * RegistryEntry implementation for loading PNG images through Image I/O. 23 | * 24 | * @version $Id$ 25 | */ 26 | public class ImageIOPNGRegistryEntry 27 | extends AbstractImageIORegistryEntry { 28 | 29 | 30 | static final byte [] signature = {(byte)0x89, 80, 78, 71, 13, 10, 26, 10}; 31 | 32 | public ImageIOPNGRegistryEntry() { 33 | super("PNG", "png", "image/png", 0, signature); 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /victor/src/main/java/org/apache/batik/ext/awt/image/codec/imageio/ImageIOJPEGRegistryEntry.java: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Licensed to the Apache Software Foundation (ASF) under one or more 4 | contributor license agreements. See the NOTICE file distributed with 5 | this work for additional information regarding copyright ownership. 6 | The ASF licenses this file to You under the Apache License, Version 2.0 7 | (the "License"); you may not use this file except in compliance with 8 | the License. You may obtain a copy of the License at 9 | 10 | http://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 | package org.apache.batik.ext.awt.image.codec.imageio; 20 | 21 | /** 22 | * RegistryEntry implementation for loading JPEG images through Image I/O. 23 | * 24 | * @version $Id$ 25 | */ 26 | public class ImageIOJPEGRegistryEntry 27 | extends AbstractImageIORegistryEntry { 28 | 29 | static final byte [] sigJPEG = {(byte)0xFF, (byte)0xd8, 30 | (byte)0xFF}; 31 | static final String [] exts = {"jpeg", "jpg" }; 32 | static final String [] mimeTypes = {"image/jpeg", "image/jpg" }; 33 | static final MagicNumber [] magicNumbers = { 34 | new MagicNumber(0, sigJPEG) 35 | }; 36 | 37 | public ImageIOJPEGRegistryEntry() { 38 | super("JPEG", exts, mimeTypes, magicNumbers); 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Built application files 2 | *.apk 3 | *.aar 4 | *.ap_ 5 | *.aab 6 | 7 | # Files for the ART/Dalvik VM 8 | *.dex 9 | 10 | # Java class files 11 | *.class 12 | 13 | # Generated files 14 | bin/ 15 | gen/ 16 | out/ 17 | # Uncomment the following line in case you need and you don't have the release build type files in your app 18 | # release/ 19 | 20 | # Gradle files 21 | .gradle/ 22 | build/ 23 | 24 | # Local configuration file (sdk path, etc) 25 | local.properties 26 | 27 | # Proguard folder generated by Eclipse 28 | proguard/ 29 | 30 | # Log Files 31 | *.log 32 | 33 | # Android Studio Navigation editor temp files 34 | .navigation/ 35 | 36 | # Android Studio captures folder 37 | captures/ 38 | 39 | # IntelliJ 40 | *.iml 41 | .idea/workspace.xml 42 | .idea/tasks.xml 43 | .idea/gradle.xml 44 | .idea/assetWizardSettings.xml 45 | .idea/dictionaries 46 | .idea/libraries 47 | # Android Studio 3 in .gitignore file. 48 | .idea/caches 49 | .idea/modules.xml 50 | # Comment next line if keeping position of elements in Navigation Editor is relevant for you 51 | .idea/navEditor.xml 52 | 53 | # Keystore files 54 | # Uncomment the following lines if you do not want to check your keystore files in. 55 | #*.jks 56 | #*.keystore 57 | 58 | # External native build folder generated in Android Studio 2.2 and later 59 | .externalNativeBuild 60 | .cxx/ 61 | 62 | # Google Services (e.g. APIs or Firebase) 63 | # google-services.json 64 | 65 | # Freeline 66 | freeline.py 67 | freeline/ 68 | freeline_project_description.json 69 | 70 | # fastlane 71 | fastlane/report.xml 72 | fastlane/Preview.html 73 | fastlane/screenshots 74 | fastlane/test_output 75 | fastlane/readme.md 76 | 77 | # Version control 78 | vcs.xml 79 | 80 | # lint 81 | lint/intermediates/ 82 | lint/generated/ 83 | lint/outputs/ 84 | lint/tmp/ 85 | # lint/reports/ -------------------------------------------------------------------------------- /victor/src/main/java/org/apache/batik/ext/awt/image/codec/imageio/ImageIOTIFFRegistryEntry.java: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Licensed to the Apache Software Foundation (ASF) under one or more 4 | contributor license agreements. See the NOTICE file distributed with 5 | this work for additional information regarding copyright ownership. 6 | The ASF licenses this file to You under the Apache License, Version 2.0 7 | (the "License"); you may not use this file except in compliance with 8 | the License. You may obtain a copy of the License at 9 | 10 | http://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 | package org.apache.batik.ext.awt.image.codec.imageio; 20 | 21 | import org.apache.batik.ext.awt.image.spi.MagicNumberRegistryEntry; 22 | 23 | /** 24 | * RegistryEntry implementation for loading TIFF images through Image I/O. 25 | * 26 | * @version $Id$ 27 | */ 28 | public class ImageIOTIFFRegistryEntry 29 | extends AbstractImageIORegistryEntry { 30 | 31 | static final byte [] sig1 = {(byte)0x49, (byte)0x49, 42, 0}; 32 | static final byte [] sig2 = {(byte)0x4D, (byte)0x4D, 0, 42}; 33 | 34 | static MagicNumberRegistryEntry.MagicNumber [] magicNumbers = { 35 | new MagicNumberRegistryEntry.MagicNumber(0, sig1), 36 | new MagicNumberRegistryEntry.MagicNumber(0, sig2) }; 37 | 38 | static final String [] exts = {"tiff", "tif" }; 39 | static final String [] mimeTypes = {"image/tiff", "image/tif" }; 40 | 41 | public ImageIOTIFFRegistryEntry() { 42 | super("TIFF", exts, mimeTypes, magicNumbers); 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /victor/src/main/groovy/com/trello/victor/VictorPluginExtension.groovy: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Trello, Inc 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.trello.victor 18 | 19 | /** 20 | * Configuration values for the victor {} script block. 21 | */ 22 | class VictorPluginExtension { 23 | 24 | /** 25 | * The DPI to use for SVG assets whose size is defined in relative terms. 26 | * 27 | * For example, if the size is 1in x 1in, you would need to define how many 28 | * pixels are in an inch. 29 | * 30 | * This value is ignored for SVGs whose size are defined in absolute terms. 31 | * 32 | * The default value is 72 DPI. 33 | */ 34 | int svgDpi = 72 35 | 36 | /** 37 | * Densities to exclude when generating SVG assets. 38 | * 39 | * If not set, all densities are generated. 40 | * 41 | * Possible values: ldpi, mdpi, hdpi, xhdpi, xxhdpi, xxxhpdi 42 | */ 43 | List excludeDensities = [] 44 | 45 | /** 46 | * [Experimental] 47 | * 48 | * If set to true, Victor will generate Android vector drawables 49 | * If not, it will generate PNGs in all specified densities 50 | * 51 | * Note that the svgDpi and excludeDensities are ignored if 52 | * generateVectorDrawables is set to true 53 | * 54 | * The default value is false 55 | */ 56 | boolean generateVectorDrawables = false 57 | 58 | } 59 | -------------------------------------------------------------------------------- /victor/src/test/groovy/com/trello/victor/SVGResourceTests.groovy: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Trello, Inc 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.trello.victor 18 | import org.junit.Test 19 | 20 | import static org.junit.Assert.assertEquals 21 | 22 | class SVGResourceTests { 23 | 24 | private final static RESOURCE_PATH = './src/test/resources/' 25 | 26 | @Test 27 | void canGetRelativeSize() { 28 | File svgFile = new File(RESOURCE_PATH, 'relative.svg') 29 | SVGResource svgResource = new SVGResource(svgFile, 72) 30 | assertEquals(24, svgResource.width) 31 | assertEquals(24, svgResource.height) 32 | } 33 | 34 | @Test 35 | void canReadPixelSize() { 36 | File svgFile = new File(RESOURCE_PATH, 'pixel.svg') 37 | SVGResource svgResource = new SVGResource(svgFile, 72) 38 | assertEquals(24, svgResource.width) 39 | assertEquals(24, svgResource.height) 40 | } 41 | 42 | @Test 43 | void ignoresNonexistantFiles() { 44 | // Simply tests that it doesn't crash 45 | File svgFile = new File('does-not-exist.svg') 46 | new SVGResource(svgFile, 72) 47 | } 48 | 49 | @Test 50 | void invalidSvg() { 51 | File svgFile = new File(RESOURCE_PATH, 'invalid.svg') 52 | 53 | // This is simply testing that it doesn't blow up if you pass it an invalid file 54 | SVGResource svgResource = new SVGResource(svgFile, 72) 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | Change Log 2 | ========== 3 | 4 | 1.1.2 5 | ----- 6 | *2021-06-08* 7 | 8 | - ([#81](https://github.com/trello/victor/pull/81), [#83](https://github.com/trello/victor/pull/83), [#84](https://github.com/trello/victor/pull/84), [#85](https://github.com/trello/victor/pull/85)) Added Gradle 7 support. 9 | 10 | 1.1.1 11 | ----- 12 | *2021-03-24* 13 | 14 | There are no differences between 1.1.0 and 1.1.1; we simply moved to a different host, and I wanted 15 | to make sure there was no confusion when switching over (since builds will fail now if you keep 16 | trying to access this via jcenter). 17 | 18 | - ([#78](https://github.com/trello/victor/pull/78)) Moved to Gradle publishing portal 19 | 20 | 1.1.0 21 | ----- 22 | *2020-05-08* 23 | 24 | - ([#71](https://github.com/trello/victor/pull/71)) Added support for Gradle 6 25 | - ([#72](https://github.com/trello/victor/pull/72)) Upgraded to Batik 1.12 26 | 27 | 1.0.0 28 | ----- 29 | *2017-07-19* 30 | 31 | I'm calling this 1.0 for no other reason than that this is going to be considered stable; no major 32 | changes to the API from here on out. 33 | 34 | - ([#65](https://github.com/trello/victor/pull/65)) Upgraded to Batik 1.9 35 | 36 | 0.3.0 37 | ----- 38 | *2016-06-14* 39 | 40 | - ([#43](https://github.com/trello/victor/pull/43)) Experimental SVG -> Android drawable support 41 | 42 | 0.2.0 43 | ----- 44 | *2016-03-24* 45 | 46 | - ([#40](https://github.com/trello/victor/pull/40)) Fixed some codec issues with Batik 1.8 47 | - ([#38](https://github.com/trello/victor/pull/38)) Support Gradle 2.12 48 | 49 | 0.1.5 50 | ----- 51 | *2015-08-07* 52 | 53 | - (#28) Upgraded underlying rasterization lib to batik 1.8 54 | 55 | 0.1.4 56 | ----- 57 | *2015-05-07* 58 | 59 | - (#17) Fixed rasterize task being needlessly re-executed when using the Gradle daemon 60 | 61 | 0.1.3 62 | ----- 63 | *2015-04-30* 64 | 65 | - (#14) Added support for using Victor in Android libraries 66 | 67 | 0.1.2 68 | ----- 69 | *2015-03-10* 70 | 71 | - Fixed plugin when no excluded densities are defined 72 | 73 | 0.1.1 74 | ----- 75 | *2015-03-10* 76 | 77 | - #8: Handle invalid SVGs gracefully 78 | 79 | 0.1.0 80 | ----- 81 | *2015-03-03* 82 | 83 | Initial release! It has support for defining SVG sourcesets and rasterizing them for use as resources. 84 | -------------------------------------------------------------------------------- /sample/build.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Trello, Inc 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | buildscript { 18 | repositories { 19 | maven { 20 | url "https://plugins.gradle.org/m2/" 21 | } 22 | } 23 | dependencies { 24 | classpath 'com.trello:victor:1.1.2' 25 | } 26 | } 27 | 28 | apply plugin: 'com.android.application' 29 | 30 | // Make sure to apply this plugin *after* the Android plugin 31 | apply plugin: 'com.trello.victor' 32 | 33 | android { 34 | compileSdkVersion 30 35 | 36 | defaultConfig { 37 | applicationId "com.trello.victorsample" 38 | minSdkVersion 15 39 | targetSdkVersion 30 40 | versionCode 1 41 | versionName "1.0" 42 | 43 | // In case you use generateVectorDrawables = true 44 | vectorDrawables.useSupportLibrary = true 45 | } 46 | 47 | compileOptions { 48 | sourceCompatibility JavaVersion.VERSION_1_8 49 | targetCompatibility JavaVersion.VERSION_1_8 50 | } 51 | 52 | // Define the 'svg' source set for any flavors/build types and/or 'main' for all of them 53 | sourceSets { 54 | main { 55 | svg.srcDir 'src/main/svg' 56 | } 57 | } 58 | } 59 | 60 | victor { 61 | // Any assets defined in relative terms needs a base DPI specified 62 | svgDpi = 72 63 | 64 | // Do not generate these densities for SVG assets 65 | excludeDensities = [ 'ldpi', 'xxxhdpi' ] 66 | 67 | // Set this to "true" if you want to generate Android vectors instead of PNGs 68 | generateVectorDrawables = false 69 | } 70 | 71 | repositories { 72 | maven { 73 | url "https://maven.google.com" 74 | } 75 | } 76 | 77 | dependencies { 78 | implementation 'androidx.appcompat:appcompat:1.3.0' 79 | } 80 | -------------------------------------------------------------------------------- /victor/build.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Trello, Inc 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | plugins { 18 | id 'java-gradle-plugin' 19 | id "com.gradle.plugin-publish" version "0.13.0" 20 | id 'maven-publish' 21 | id 'groovy' 22 | } 23 | 24 | dependencies { 25 | implementation gradleApi() 26 | implementation localGroovy() 27 | } 28 | 29 | // This makes it easier to figure out issues with Travis CI builds 30 | test { 31 | testLogging.showStandardStreams = true 32 | } 33 | 34 | repositories { 35 | mavenCentral() 36 | } 37 | 38 | sourceCompatibility = 1.8 39 | targetCompatibility = 1.8 40 | 41 | // Batik dependencies 42 | 43 | dependencies { 44 | implementation 'org.apache.xmlgraphics:batik-codec:1.12' 45 | implementation 'org.apache.xmlgraphics:batik-anim:1.12' 46 | implementation 'org.apache.xmlgraphics:xmlgraphics-commons:2.4' 47 | implementation 'com.romainpiel.svgtoandroid:svgtoandroid:0.1.0' 48 | testImplementation 'junit:junit:4.13.2' 49 | } 50 | 51 | // Plugin publishing 52 | 53 | group = 'com.trello' 54 | version = '1.1.2-SNAPSHOT' 55 | 56 | 57 | gradlePlugin { 58 | plugins { 59 | victorPlugin { 60 | id = 'com.trello.victor' 61 | implementationClass = 'com.trello.victor.VictorPlugin' 62 | } 63 | } 64 | } 65 | 66 | pluginBundle { 67 | website = 'https://github.com/trello/victor' 68 | vcsUrl = 'https://github.com/trello/victor' 69 | description = 'Gradle plugin that lets an Android project use SVGs as resources.' 70 | tags = ['gradle', 'plugin', 'android'] 71 | 72 | plugins { 73 | victorPlugin { 74 | displayName = 'victor' 75 | } 76 | } 77 | 78 | mavenCoordinates { 79 | groupId = "com.trello" 80 | artifactId = "victor" 81 | } 82 | } 83 | 84 | publishing { 85 | repositories { 86 | maven { 87 | name = 'localPluginRepository' 88 | url = '../local-plugin-repository' 89 | } 90 | } 91 | } -------------------------------------------------------------------------------- /sample/build.gradle.kts.example: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Trello, Inc 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | buildscript { 18 | repositories { 19 | maven { 20 | url = uri("https://plugins.gradle.org/m2/") 21 | } 22 | } 23 | dependencies { 24 | classpath("com.trello:victor:1.1.2") 25 | } 26 | } 27 | 28 | plugins { 29 | id("com.android.application") 30 | } 31 | 32 | // Make sure to apply this plugin *after* the Android plugin 33 | apply(plugin = "com.trello.victor") 34 | 35 | val Any.extensions get() = (this as org.gradle.api.plugins.ExtensionAware).extensions 36 | 37 | android { 38 | compileSdkVersion(30) 39 | 40 | defaultConfig { 41 | applicationId = "com.trello.victorsample" 42 | minSdkVersion(15) 43 | targetSdkVersion(30) 44 | versionCode = 1 45 | versionName = "1.0" 46 | 47 | // In case you val generateVectorDrawables: use = true 48 | vectorDrawables.useSupportLibrary = true 49 | } 50 | compileOptions { 51 | sourceCompatibility = JavaVersion.VERSION_1_8 52 | targetCompatibility = JavaVersion.VERSION_1_8 53 | } 54 | sourceSets { 55 | // Example with setting one 56 | named("main") { 57 | val svgSourceSet = this.extensions["svg"] as SourceDirectorySet 58 | svgSourceSet.srcDir("src/${name}/svg") 59 | } 60 | } 61 | // Example setting all 62 | sourceSets.all { 63 | val svgSourceSet = this.extensions["svg"] as SourceDirectorySet 64 | svgSourceSet.srcDir("src/${name}/svg") 65 | } 66 | } 67 | configure { 68 | // Any assets defined in relative terms needs a base DPI specified 69 | svgDpi = 72 70 | 71 | // Do not generate these densities for SVG assets 72 | excludeDensities = listOf("ldpi", "xxxhdpi") 73 | 74 | // Set this to "true" if you want to generate Android vectors instead of PNGs 75 | generateVectorDrawables = false 76 | } 77 | 78 | dependencies { 79 | implementation("androidx.appcompat:appcompat:1.2.0") 80 | } 81 | -------------------------------------------------------------------------------- /victor/src/main/groovy/com/trello/victor/Converter.groovy: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Trello, Inc 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.trello.victor 18 | 19 | import org.apache.batik.transcoder.Transcoder 20 | import org.apache.batik.transcoder.TranscoderException 21 | import org.apache.batik.transcoder.TranscoderInput 22 | import org.apache.batik.transcoder.TranscoderOutput 23 | import org.apache.batik.transcoder.image.ImageTranscoder 24 | import org.apache.batik.transcoder.image.PNGTranscoder 25 | import org.gradle.api.logging.Logging 26 | 27 | /** 28 | * Converts SVGs to PNGs. 29 | * 30 | * This is split out into its own class to make it easier to test (since it doesn't require 31 | * any of the Task architecture). 32 | */ 33 | class Converter { 34 | 35 | private Transcoder transcoder = new PNGTranscoder() 36 | 37 | /** 38 | * Transcodes an SVGResource into a PNG. 39 | * 40 | * @param svgResource the input SVG 41 | * @param density the density to output the PNG; determines scaling 42 | * @param destination the output destination 43 | */ 44 | void transcode(SVGResource svgResource, Density density, File destination) { 45 | if (!svgResource.canBeRead) { 46 | Logging.getLogger(this.class) 47 | .warn("Cannot convert SVGResource $svgResource.file.name; file cannot be parsed") 48 | return 49 | } 50 | 51 | int outWidth = Math.round(svgResource.width * density.multiplier) 52 | int outHeight = Math.round(svgResource.height * density.multiplier) 53 | transcoder.addTranscodingHint(ImageTranscoder.KEY_WIDTH, new Float(outWidth)) 54 | transcoder.addTranscodingHint(ImageTranscoder.KEY_HEIGHT, new Float(outHeight)) 55 | 56 | String svgURI = svgResource.file.toURI().toString() 57 | TranscoderInput input = new TranscoderInput(svgURI) 58 | 59 | OutputStream outStream = new FileOutputStream(destination) 60 | TranscoderOutput output = new TranscoderOutput(outStream) 61 | 62 | try { 63 | transcoder.transcode(input, output) 64 | } 65 | catch (TranscoderException e) { 66 | Logging.getLogger(this.class).error('Could not transcode $svgResource.file.name', e) 67 | destination.delete() 68 | return 69 | } 70 | 71 | outStream.flush() 72 | outStream.close() 73 | } 74 | } -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /victor/src/main/groovy/com/trello/victor/SVGResource.groovy: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Trello, Inc 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.trello.victor 18 | 19 | import org.apache.batik.anim.dom.SAXSVGDocumentFactory 20 | import org.apache.batik.bridge.BridgeContext 21 | import org.apache.batik.bridge.UnitProcessor 22 | import org.apache.batik.bridge.UserAgent 23 | import org.apache.batik.bridge.UserAgentAdapter 24 | import org.apache.batik.util.XMLResourceDescriptor 25 | import org.gradle.api.logging.Logging 26 | import org.w3c.dom.svg.SVGDocument 27 | import org.w3c.dom.svg.SVGSVGElement 28 | 29 | /** 30 | * Automatically calculates the width and height of an SVG file. 31 | */ 32 | class SVGResource { 33 | 34 | private File file 35 | 36 | // Basic way to tell if we could read the file or not 37 | private boolean canBeRead = false 38 | 39 | // Data read from the file, if it exists 40 | private int width 41 | private int height 42 | 43 | SVGResource(File file, int dpi) { 44 | this.file = file 45 | 46 | readSvgInfo(dpi) 47 | } 48 | 49 | private void readSvgInfo(int dpi) { 50 | if (!file.exists()) { 51 | return 52 | } 53 | 54 | String parser = XMLResourceDescriptor.getXMLParserClassName() 55 | SAXSVGDocumentFactory factory = new SAXSVGDocumentFactory(parser) 56 | SVGDocument document 57 | try { 58 | document = (SVGDocument) factory.createDocument(file.toURI().toString()) 59 | } 60 | catch (IOException e) { 61 | Logging.getLogger(this.class).error("Could not read SVG resource $file.name", e) 62 | return 63 | } 64 | 65 | SVGSVGElement svgElement = document.getRootElement() 66 | 67 | UserAgent userAgent = new DensityUserAgent(dpi) 68 | BridgeContext bridgeContext = new BridgeContext(userAgent) 69 | org.apache.batik.parser.UnitProcessor.Context context = UnitProcessor.createContext(bridgeContext, svgElement) 70 | 71 | width = UnitProcessor.svgHorizontalLengthToUserSpace(svgElement.width.baseVal.valueAsString, '', context) 72 | height = UnitProcessor.svgVerticalLengthToUserSpace(svgElement.height.baseVal.valueAsString, '', context) 73 | 74 | canBeRead = true 75 | } 76 | 77 | private static final class DensityUserAgent extends UserAgentAdapter { 78 | 79 | private float pixelUnitToMillimeter 80 | 81 | private DensityUserAgent(int dpi) { 82 | pixelUnitToMillimeter = (2.54f / dpi) * 10 83 | } 84 | 85 | @Override 86 | float getPixelUnitToMillimeter() { 87 | return pixelUnitToMillimeter 88 | } 89 | } 90 | } -------------------------------------------------------------------------------- /victor/src/main/groovy/com/trello/victor/VictorPlugin.groovy: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Trello, Inc 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.trello.victor 18 | 19 | import org.gradle.api.Plugin 20 | import org.gradle.api.Project 21 | import org.gradle.api.Task 22 | import org.gradle.api.file.FileCollection 23 | import org.gradle.api.file.SourceDirectorySet 24 | 25 | class VictorPlugin implements Plugin { 26 | 27 | void apply(Project project) { 28 | project.extensions.create('victor', VictorPluginExtension) 29 | 30 | // Add 'svg' as a source set extension 31 | project.android.sourceSets.all { sourceSet -> 32 | SourceDirectorySet sds = project.objects.sourceDirectorySet(sourceSet.name, "${sourceSet.name} svgs") 33 | sourceSet.extensions.add('svg', sds) 34 | } 35 | 36 | project.afterEvaluate { 37 | List densities = Density.values() 38 | project.victor.excludeDensities.each { String density -> 39 | densities.remove(Density.valueOf(density.toUpperCase())) 40 | } 41 | 42 | // Keep order consistent 43 | densities = densities.sort() 44 | 45 | def variants = null 46 | if (project.android.hasProperty('applicationVariants')) { 47 | variants = project.android.applicationVariants 48 | } 49 | else if (project.android.hasProperty('libraryVariants')) { 50 | variants = project.android.libraryVariants 51 | } 52 | else { 53 | throw new IllegalStateException('Android project must have applicationVariants or libraryVariants!') 54 | } 55 | 56 | // Register our task with the variant's resources 57 | variants.all { variant -> 58 | // TODO: Use lazier evaluation for files by sticking this in a prep task? 59 | FileCollection svgFiles = project.files() 60 | variant.sourceSets.each { sourceSet -> 61 | FileCollection filteredCollection = sourceSet.svg.filter { File file -> 62 | file.name.endsWith '.svg' 63 | } 64 | svgFiles.from filteredCollection 65 | } 66 | 67 | if (svgFiles.empty) { 68 | return 69 | } 70 | 71 | 72 | File conversionOutputDir = project.file("$project.buildDir/generated/res/$flavorName/$buildType.name/svg/") 73 | Task conversionTask = project.task("rasterizeSvgsFor${variant.name.capitalize()}", type: RasterizeTask) { 74 | sources = svgFiles 75 | outputDir = conversionOutputDir 76 | includeDensities = densities 77 | baseDpi = project.victor.svgDpi 78 | generateVectorDrawables = project.victor.generateVectorDrawables 79 | } 80 | 81 | // Makes the magic happen (inserts resources so devs can use it) 82 | variant.registerResGeneratingTask(conversionTask, conversionTask.outputDir) 83 | } 84 | } 85 | } 86 | } -------------------------------------------------------------------------------- /.idea/codeStyles/Project.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 |
7 | 8 | 9 | 10 | xmlns:android 11 | 12 | ^$ 13 | 14 | 15 | 16 |
17 |
18 | 19 | 20 | 21 | xmlns:.* 22 | 23 | ^$ 24 | 25 | 26 | BY_NAME 27 | 28 |
29 |
30 | 31 | 32 | 33 | .*:id 34 | 35 | http://schemas.android.com/apk/res/android 36 | 37 | 38 | 39 |
40 |
41 | 42 | 43 | 44 | .*:name 45 | 46 | http://schemas.android.com/apk/res/android 47 | 48 | 49 | 50 |
51 |
52 | 53 | 54 | 55 | name 56 | 57 | ^$ 58 | 59 | 60 | 61 |
62 |
63 | 64 | 65 | 66 | style 67 | 68 | ^$ 69 | 70 | 71 | 72 |
73 |
74 | 75 | 76 | 77 | .* 78 | 79 | ^$ 80 | 81 | 82 | BY_NAME 83 | 84 |
85 |
86 | 87 | 88 | 89 | .* 90 | 91 | http://schemas.android.com/apk/res/android 92 | 93 | 94 | ANDROID_ATTRIBUTE_ORDER 95 | 96 |
97 |
98 | 99 | 100 | 101 | .* 102 | 103 | .* 104 | 105 | 106 | BY_NAME 107 | 108 |
109 |
110 |
111 |
112 |
113 |
-------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | victor 2 | ====== 3 | 4 | *What's our vector, Victor? -Captain Oveur* 5 | 6 | Use SVGs as resources in Android! 7 | 8 | With this plugin, you can define source folders for SVGs and they will automatically be rasterized/included in your build without messing with your source code. 9 | 10 | Installation 11 | ------------ 12 | 13 | Add the following to your `build.gradle`: 14 | 15 | ```gradle 16 | buildscript { 17 | repositories { 18 | maven { 19 | url "https://plugins.gradle.org/m2/" 20 | } 21 | } 22 | dependencies { 23 | classpath 'com.trello:victor:1.1.2' 24 | } 25 | } 26 | 27 | apply plugin: 'com.android.application' 28 | 29 | // Make sure to apply this plugin *after* the Android plugin 30 | apply plugin: 'com.trello.victor' 31 | ``` 32 | 33 | Usage 34 | ----- 35 | 36 | Victor adds the `svg` source set to the Android plugin. You can define where your SVG folders are in the same way you define any other source sets: 37 | 38 | ```gradle 39 | android { 40 | sourceSets { 41 | main { 42 | svg.srcDir 'src/main/svg' 43 | } 44 | } 45 | sourceSets.all { // this sets for all at once 46 | svg.srcDir "src/${name}/svg" 47 | } 48 | } 49 | ``` 50 | 51 | You can have multiple SVG folders for a variety of build types/product flavors; or you can just use 'main' to cover them all. 52 | 53 | Additional configuration can be done in the `victor` closure: 54 | 55 | ```gradle 56 | victor { 57 | // Any assets defined in relative terms needs a base DPI specified 58 | svgDpi = 72 59 | 60 | // Do not generate these densities for SVG assets 61 | excludeDensities = [ 'ldpi', 'xxxhdpi' ] 62 | 63 | // WARNING: EXPERIMENTAL 64 | // Generates Android drawables instead of PNGs. 65 | // 66 | // This is known not to work on only a subset of SVGs (e.g., does not support any value besides px). 67 | generateVectorDrawables = true 68 | } 69 | ``` 70 | 71 | Usage (Kotlin) 72 | ----- 73 | 74 | Here's how to configure the Victors svg source-set extension via Gradle Kotlin DSL, with both an example for an individual source-set and for setting for all source-sets. 75 | 76 | ```Kotlin 77 | val Any.extensions get() = (this as org.gradle.api.plugins.ExtensionAware).extensions 78 | android { 79 | sourceSets { 80 | // Example with setting one 81 | named("main") { 82 | val svgSourceSet = this.extensions["svg"] as SourceDirectorySet 83 | svgSourceSet.srcDir("src/${name}/svg") 84 | } 85 | } 86 | // Example setting all 87 | sourceSets.all { 88 | val svgSourceSet = this.extensions["svg"] as SourceDirectorySet 89 | svgSourceSet.srcDir("src/${name}/svg") 90 | } 91 | } 92 | ``` 93 | 94 | You can have multiple SVG folders for a variety of build types/product flavors; or you can just use 'main' to cover them all. 95 | 96 | Additional configuration can be done in the `victor` closure: 97 | 98 | ```kotlin 99 | configure { 100 | // See comments in gradle section 101 | svgDpi = 72 102 | excludeDensities = [ 'ldpi', 'xxxhdpi' ] 103 | generateVectorDrawables = true 104 | } 105 | ``` 106 | 107 | 108 | OSX Issues 109 | ---------- 110 | 111 | When using Android Studio on OSX, you might see this error: 112 | 113 | `Toolkit not found: apple.awt.CToolkit` 114 | 115 | This occurs because [Batik](http://xmlgraphics.apache.org/batik/), the SVG toolkit Victor uses, requires a working version of AWT. 116 | 117 | If this happens you should install and use [JDK 1.7](http://www.oracle.com/technetwork/java/javase/downloads/jdk7-downloads-1880260.html) for your instance of Android Studio. For instructions how, consult the "Mac OS X" section of [this article](https://intellij-support.jetbrains.com/entries/23455956-Selecting-the-JDK-version-the-IDE-will-run-under). 118 | 119 | Known Issues 120 | ------------ 121 | 122 | - Android Studio doesn't recognize generated resources in XML, so autocomplete doesn't work and you get warnings (even though the code works fine). Generated resources should be fully supported in future versions of the Android Gradle plugin. 123 | 124 | - Android Studio doesn't automatically rebuild if the SVG folder is modified (like it does with other resources). Therefore, if you add SVGs you will have to manually rebuild before they will be generated. 125 | 126 | - Due to bugs in Batik, the SVG toolkit used by Victor, some SVGs containing 'mask="url(#mask-2)"' references are not rasterized correctly. Sketch and other tools occasionally produce assets with these references. 127 | 128 | Planned Features 129 | ---------------- 130 | 131 | - 9-patch support 132 | -------------------------------------------------------------------------------- /victor/src/main/groovy/com/trello/victor/RasterizeTask.groovy: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Trello, Inc 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.trello.victor 18 | 19 | import com.romainpiel.svgtoandroid.Svg2Vector 20 | import org.gradle.api.DefaultTask 21 | import org.gradle.api.GradleException 22 | import org.gradle.api.file.FileCollection 23 | import org.gradle.api.tasks.Input 24 | import org.gradle.api.tasks.InputFiles 25 | import org.gradle.api.tasks.OutputDirectory 26 | import org.gradle.api.tasks.TaskAction 27 | import org.gradle.api.tasks.incremental.IncrementalTaskInputs 28 | import org.gradle.api.tasks.incremental.InputFileDetails 29 | 30 | import javax.annotation.Nullable 31 | 32 | /** 33 | * Task that rasterizes SVGs into PNGs. 34 | */ 35 | class RasterizeTask extends DefaultTask { 36 | 37 | /** 38 | * The input SVGs. 39 | */ 40 | @InputFiles 41 | FileCollection sources 42 | 43 | /** 44 | * The output directory. 45 | */ 46 | @OutputDirectory 47 | File outputDir 48 | 49 | /** 50 | * The densities to scale assets for. 51 | */ 52 | @Input 53 | List includeDensities 54 | 55 | /** 56 | * There is a bug determining whether this task is up-to-date with 57 | * `includeDensities`: because it is a List, it fails when you 58 | * have the daemon running the build. This method is provided as a 59 | * workaround to test up-to-dateness, but should never actually used 60 | * beyond that. 61 | * 62 | * References: 63 | * - https://discuss.gradle.org/t/custom-task-never-up-to-date-when-running-daemon/9525 64 | * - https://issues.gradle.org/browse/GRADLE-3018 65 | */ 66 | @Input 67 | List getDensitiesWorkaround() { 68 | includeDensities.collect { it.toString() } 69 | } 70 | 71 | /** 72 | * The DPI to use for relative-sized SVGs. 73 | */ 74 | @Input 75 | int baseDpi 76 | 77 | /** 78 | * Flag to generate android vectors instead of PNGs 79 | */ 80 | @Input 81 | boolean generateVectorDrawables; 82 | 83 | @TaskAction 84 | def rasterize(IncrementalTaskInputs inputs) { 85 | // If the whole thing isn't incremental, delete the build folder (if it exists) 86 | if (!inputs.isIncremental() && outputDir.exists()) { 87 | logger.debug("SVG rasterization is not incremental; deleting build folder and starting fresh!") 88 | outputDir.delete() 89 | } 90 | 91 | List svgFiles = [] 92 | inputs.outOfDate { InputFileDetails change -> 93 | logger.debug("$change.file.name out of date; converting") 94 | svgFiles.add change.file 95 | } 96 | 97 | // Make sure all output directories exist 98 | if (generateVectorDrawables) { 99 | createOutput() 100 | } else { 101 | includeDensities.each { Density density -> 102 | createOutput(density) 103 | } 104 | } 105 | 106 | if (generateVectorDrawables) { 107 | svgFiles.each { File svgFile -> 108 | File resDir = resourceDir() 109 | File destination = new File(resDir, destinationFile(svgFile.name, 'xml')) 110 | OutputStream outStream = new FileOutputStream(destination) 111 | String error = Svg2Vector.parseSvgToXml(svgFile, outStream) 112 | if (!error.isEmpty()) { 113 | logger.error(error) 114 | throw new GradleException(error) 115 | } 116 | 117 | outStream.flush() 118 | outStream.close() 119 | 120 | logger.info("Converted $svgFile to $destination") 121 | } 122 | } else { 123 | Converter converter = new Converter() 124 | svgFiles.each { File svgFile -> 125 | SVGResource svgResource = new SVGResource(svgFile, baseDpi) 126 | 127 | includeDensities.each { Density density -> 128 | File destination = new File(resourceDir(density), destinationFile(svgFile.name, 'png')) 129 | converter.transcode(svgResource, density, destination) 130 | logger.info("Converted $svgFile to $destination") 131 | } 132 | } 133 | } 134 | 135 | inputs.removed { change -> 136 | logger.debug("$change.file.name was removed; removing it from generated folder") 137 | 138 | if (generateVectorDrawables) { 139 | File resDir = resourceDir() 140 | File file = new File(resDir, destinationFile(inputFileDetails.file.name, 'xml')) 141 | file.delete() 142 | } else { 143 | includeDensities.each { Density density -> 144 | File resDir = resourceDir(density) 145 | File file = new File(resDir, destinationFile(inputFileDetails.file.name, 'png')) 146 | file.delete() 147 | } 148 | } 149 | } 150 | } 151 | 152 | void createOutput(@Nullable Density density = null) { 153 | File resDir = resourceDir(density) 154 | resDir.mkdirs() 155 | } 156 | 157 | File resourceDir(@Nullable Density density = null) { 158 | String suffix = density? "-${density.name().toLowerCase()}" : "" 159 | return new File(outputDir, "/drawable${suffix}") 160 | } 161 | 162 | String destinationFile(String name, String suffix) { 163 | int suffixStart = name.lastIndexOf '.' 164 | return suffixStart == -1 ? name : "${name.substring(0, suffixStart)}.$suffix" 165 | } 166 | } -------------------------------------------------------------------------------- /victor/src/main/java/org/apache/batik/ext/awt/image/codec/imageio/ImageIOJPEGImageWriter.java: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Licensed to the Apache Software Foundation (ASF) under one or more 4 | contributor license agreements. See the NOTICE file distributed with 5 | this work for additional information regarding copyright ownership. 6 | The ASF licenses this file to You under the Apache License, Version 2.0 7 | (the "License"); you may not use this file except in compliance with 8 | the License. You may obtain a copy of the License at 9 | 10 | http://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 | package org.apache.batik.ext.awt.image.codec.imageio; 20 | 21 | import java.awt.image.RenderedImage; 22 | 23 | import javax.imageio.ImageWriteParam; 24 | import javax.imageio.ImageWriter; 25 | import javax.imageio.metadata.IIOInvalidTreeException; 26 | import javax.imageio.metadata.IIOMetadata; 27 | import javax.imageio.metadata.IIOMetadataNode; 28 | import javax.imageio.plugins.jpeg.JPEGImageWriteParam; 29 | 30 | import org.apache.batik.ext.awt.image.spi.ImageWriterParams; 31 | 32 | /** 33 | * ImageWriter that encodes JPEG images using Image I/O. 34 | * 35 | * @version $Id$ 36 | */ 37 | public class ImageIOJPEGImageWriter extends ImageIOImageWriter { 38 | 39 | private static final String JPEG_NATIVE_FORMAT = "javax_imageio_jpeg_image_1.0"; 40 | 41 | /** 42 | * Main constructor. 43 | */ 44 | public ImageIOJPEGImageWriter() { 45 | super("image/jpeg"); 46 | } 47 | 48 | /** {@inheritDoc} */ 49 | @Override 50 | protected IIOMetadata updateMetadata(IIOMetadata meta, ImageWriterParams params) { 51 | //ImageIODebugUtil.dumpMetadata(meta); 52 | if (JPEG_NATIVE_FORMAT.equals(meta.getNativeMetadataFormatName())) { 53 | meta = addAdobeTransform(meta); 54 | 55 | IIOMetadataNode root = (IIOMetadataNode)meta.getAsTree(JPEG_NATIVE_FORMAT); 56 | 57 | IIOMetadataNode jv = getChildNode(root, "JPEGvariety"); 58 | if (jv == null) { 59 | jv = new IIOMetadataNode("JPEGvariety"); 60 | root.appendChild(jv); 61 | } 62 | IIOMetadataNode child; 63 | if (params.getResolution() != null) { 64 | child = getChildNode(jv, "app0JFIF"); 65 | if (child == null) { 66 | child = new IIOMetadataNode("app0JFIF"); 67 | jv.appendChild(child); 68 | } 69 | //JPEG gets special treatment because there seems to be a bug in 70 | //the JPEG codec in ImageIO converting the pixel size incorrectly 71 | //(or not at all) when using standard metadata format. 72 | child.setAttribute("majorVersion", null); 73 | child.setAttribute("minorVersion", null); 74 | child.setAttribute("resUnits", "1"); //dots per inch 75 | child.setAttribute("Xdensity", params.getResolution().toString()); 76 | child.setAttribute("Ydensity", params.getResolution().toString()); 77 | child.setAttribute("thumbWidth", null); 78 | child.setAttribute("thumbHeight", null); 79 | 80 | } 81 | 82 | try { 83 | meta.setFromTree(JPEG_NATIVE_FORMAT, root); 84 | } catch (IIOInvalidTreeException e) { 85 | throw new RuntimeException("Cannot update image metadata: " 86 | + e.getMessage(), e); 87 | } 88 | 89 | //ImageIODebugUtil.dumpMetadata(meta); 90 | } 91 | 92 | return meta; 93 | } 94 | 95 | private static IIOMetadata addAdobeTransform(IIOMetadata meta) { 96 | // add the adobe transformation (transform 1 -> to YCbCr) 97 | IIOMetadataNode root = (IIOMetadataNode)meta.getAsTree(JPEG_NATIVE_FORMAT); 98 | 99 | IIOMetadataNode markerSequence = getChildNode(root, "markerSequence"); 100 | if (markerSequence == null) { 101 | throw new RuntimeException("Invalid metadata!"); 102 | } 103 | 104 | IIOMetadataNode adobeTransform = getChildNode(markerSequence, "app14Adobe"); 105 | if (adobeTransform == null) { 106 | adobeTransform = new IIOMetadataNode("app14Adobe"); 107 | adobeTransform.setAttribute("transform" , "1"); // convert RGB to YCbCr 108 | adobeTransform.setAttribute("version", "101"); 109 | adobeTransform.setAttribute("flags0", "0"); 110 | adobeTransform.setAttribute("flags1", "0"); 111 | 112 | markerSequence.appendChild(adobeTransform); 113 | } else { 114 | adobeTransform.setAttribute("transform" , "1"); 115 | } 116 | 117 | try { 118 | meta.setFromTree(JPEG_NATIVE_FORMAT, root); 119 | } catch (IIOInvalidTreeException e) { 120 | throw new RuntimeException("Cannot update image metadata: " 121 | + e.getMessage(), e); 122 | } 123 | return meta; 124 | } 125 | 126 | /** {@inheritDoc} */ 127 | @Override 128 | protected ImageWriteParam getDefaultWriteParam( 129 | ImageWriter iiowriter, RenderedImage image, 130 | ImageWriterParams params) { 131 | JPEGImageWriteParam param = new JPEGImageWriteParam(iiowriter.getLocale()); 132 | param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); 133 | param.setCompressionQuality(params.getJPEGQuality()); 134 | if (params.getCompressionMethod() != null 135 | && !"JPEG".equals(params.getCompressionMethod())) { 136 | throw new IllegalArgumentException( 137 | "No compression method other than JPEG is supported for JPEG output!"); 138 | } 139 | if (params.getJPEGForceBaseline()) { 140 | param.setProgressiveMode(JPEGImageWriteParam.MODE_DISABLED); 141 | } 142 | return param; 143 | } 144 | 145 | 146 | } 147 | -------------------------------------------------------------------------------- /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 | 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 | -------------------------------------------------------------------------------- /victor/src/main/java/org/apache/batik/ext/awt/image/codec/imageio/AbstractImageIORegistryEntry.java: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Licensed to the Apache Software Foundation (ASF) under one or more 4 | contributor license agreements. See the NOTICE file distributed with 5 | this work for additional information regarding copyright ownership. 6 | The ASF licenses this file to You under the Apache License, Version 2.0 7 | (the "License"); you may not use this file except in compliance with 8 | the License. You may obtain a copy of the License at 9 | 10 | http://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 | package org.apache.batik.ext.awt.image.codec.imageio; 20 | 21 | import java.awt.geom.Rectangle2D; 22 | import java.awt.image.BufferedImage; 23 | import java.awt.image.ColorModel; 24 | import java.awt.image.WritableRaster; 25 | import java.io.IOException; 26 | import java.io.InputStream; 27 | import java.util.Iterator; 28 | 29 | import javax.imageio.ImageIO; 30 | import javax.imageio.ImageReader; 31 | import javax.imageio.stream.ImageInputStream; 32 | 33 | import org.apache.batik.ext.awt.image.GraphicsUtil; 34 | import org.apache.batik.ext.awt.image.renderable.DeferRable; 35 | import org.apache.batik.ext.awt.image.renderable.Filter; 36 | import org.apache.batik.ext.awt.image.renderable.RedRable; 37 | import org.apache.batik.ext.awt.image.rendered.Any2sRGBRed; 38 | import org.apache.batik.ext.awt.image.rendered.CachableRed; 39 | import org.apache.batik.ext.awt.image.rendered.FormatRed; 40 | import org.apache.batik.ext.awt.image.spi.ImageTagRegistry; 41 | import org.apache.batik.ext.awt.image.spi.MagicNumberRegistryEntry; 42 | import org.apache.batik.util.ParsedURL; 43 | 44 | /** 45 | * This is the base class for all ImageIO-based RegistryEntry implementations. They 46 | * have a slightly lower priority than the RegistryEntry implementations using the 47 | * internal codecs, so these take precedence if they are available. 48 | * 49 | * @version $Id$ 50 | */ 51 | public abstract class AbstractImageIORegistryEntry 52 | extends MagicNumberRegistryEntry { 53 | 54 | /** 55 | * Constructor 56 | * @param name Format Name 57 | * @param exts Standard set of extensions 58 | * @param magicNumbers array of magic numbers any of which can match. 59 | */ 60 | public AbstractImageIORegistryEntry(String name, 61 | String [] exts, 62 | String [] mimeTypes, 63 | MagicNumber [] magicNumbers) { 64 | super(name, PRIORITY + 100, exts, mimeTypes, magicNumbers); 65 | } 66 | 67 | /** 68 | * Constructor, simplifies construction of entry when only 69 | * one extension and one magic number is required. 70 | * @param name Format Name 71 | * @param ext Standard extension 72 | * @param offset Offset of magic number 73 | * @param magicNumber byte array to match. 74 | */ 75 | public AbstractImageIORegistryEntry(String name, 76 | String ext, 77 | String mimeType, 78 | int offset, byte[] magicNumber) { 79 | super(name, PRIORITY + 100, ext, mimeType, offset, magicNumber); 80 | } 81 | 82 | /** 83 | * Decode the Stream into a RenderableImage 84 | * 85 | * @param inIS The input stream that contains the image. 86 | * @param origURL The original URL, if any, for documentation 87 | * purposes only. This may be null. 88 | * @param needRawData If true the image returned should not have 89 | * any default color correction the file may 90 | * specify applied. 91 | */ 92 | public Filter handleStream(InputStream inIS, 93 | ParsedURL origURL, 94 | boolean needRawData) { 95 | final DeferRable dr = new DeferRable(); 96 | final InputStream is = inIS; 97 | final String errCode; 98 | final Object [] errParam; 99 | if (origURL != null) { 100 | errCode = ERR_URL_FORMAT_UNREADABLE; 101 | errParam = new Object[] {getFormatName(), origURL}; 102 | } else { 103 | errCode = ERR_STREAM_FORMAT_UNREADABLE; 104 | errParam = new Object[] {getFormatName()}; 105 | } 106 | 107 | Thread t = new Thread() { 108 | @Override 109 | public void run() { 110 | Filter filt; 111 | try{ 112 | Iterator iter = ImageIO.getImageReadersByMIMEType( 113 | getMimeTypes().get(0).toString()); 114 | if (!iter.hasNext()) { 115 | throw new UnsupportedOperationException( 116 | "No image reader for " 117 | + getFormatName() + " available!"); 118 | } 119 | ImageReader reader = iter.next(); 120 | ImageInputStream imageIn = ImageIO.createImageInputStream(is); 121 | reader.setInput(imageIn, true); 122 | 123 | int imageIndex = 0; 124 | dr.setBounds(new Rectangle2D.Double 125 | (0, 0, 126 | reader.getWidth(imageIndex), 127 | reader.getHeight(imageIndex))); 128 | CachableRed cr; 129 | //Naive approach possibly wasting lots of memory 130 | //and ignoring the gamma correction done by PNGRed :-( 131 | //Matches the code used by the former JPEGRegistryEntry, though. 132 | BufferedImage bi = reader.read(imageIndex); 133 | cr = GraphicsUtil.wrap(bi); 134 | cr = new Any2sRGBRed(cr); 135 | cr = new FormatRed(cr, GraphicsUtil.sRGB_Unpre); 136 | WritableRaster wr = (WritableRaster)cr.getData(); 137 | ColorModel cm = cr.getColorModel(); 138 | BufferedImage image = new BufferedImage 139 | (cm, wr, cm.isAlphaPremultiplied(), null); 140 | cr = GraphicsUtil.wrap(image); 141 | filt = new RedRable(cr); 142 | } catch (IOException ioe) { 143 | // Something bad happened here... 144 | filt = ImageTagRegistry.getBrokenLinkImage 145 | (AbstractImageIORegistryEntry.this, 146 | errCode, errParam); 147 | } catch (ThreadDeath td) { 148 | filt = ImageTagRegistry.getBrokenLinkImage 149 | (AbstractImageIORegistryEntry.this, 150 | errCode, errParam); 151 | dr.setSource(filt); 152 | throw td; 153 | } catch (Throwable t) { 154 | filt = ImageTagRegistry.getBrokenLinkImage 155 | (AbstractImageIORegistryEntry.this, 156 | errCode, errParam); 157 | } 158 | 159 | dr.setSource(filt); 160 | } 161 | }; 162 | t.start(); 163 | return dr; 164 | } 165 | 166 | } 167 | -------------------------------------------------------------------------------- /victor/src/test/groovy/com/trello/victor/ConverterTests.groovy: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Trello, Inc 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.trello.victor 18 | 19 | import org.apache.commons.io.FileUtils 20 | import org.junit.BeforeClass 21 | import org.junit.Test 22 | import static org.junit.Assert.* 23 | 24 | class ConverterTests { 25 | 26 | private final static RESOURCE_PATH = './src/test/resources/' 27 | 28 | // TODO: Figure out a better way to get $buildDir inside of a test 29 | private final static OUT_PATH = './build/test/out/' 30 | 31 | @BeforeClass 32 | static void setup() { 33 | File destinationDir = new File(OUT_PATH) 34 | destinationDir.mkdirs() 35 | } 36 | 37 | @Test 38 | void canRasterizePng() { 39 | Converter converter = new Converter() 40 | 41 | File svgFile = new File(RESOURCE_PATH, 'rasterize.svg') 42 | SVGResource svgResource = new SVGResource(svgFile, 72) 43 | File destination = new File(OUT_PATH, 'rasterize.png') 44 | converter.transcode(svgResource, Density.MDPI, destination) 45 | 46 | assertTrue destination.exists() 47 | 48 | File expected = new File(RESOURCE_PATH, 'rasterize-expected.png') 49 | assertTrue FileUtils.contentEquals(destination, expected) 50 | } 51 | 52 | @Test 53 | void canResizePngWithRelativeSize() { 54 | Converter converter = new Converter() 55 | 56 | File svgFile = new File(RESOURCE_PATH, 'relative.svg') 57 | SVGResource svgResource = new SVGResource(svgFile, 72) 58 | 59 | File destinationLdpi = new File(OUT_PATH, 'relative-ldpi.png') 60 | converter.transcode(svgResource, Density.LDPI, destinationLdpi) 61 | 62 | File destinationMdpi = new File(OUT_PATH, 'relative-mdpi.png') 63 | converter.transcode(svgResource, Density.MDPI, destinationMdpi) 64 | 65 | File destinationHdpi = new File(OUT_PATH, 'relative-hdpi.png') 66 | converter.transcode(svgResource, Density.HDPI, destinationHdpi) 67 | 68 | File destinationXhdpi = new File(OUT_PATH, 'relative-xhdpi.png') 69 | converter.transcode(svgResource, Density.XHDPI, destinationXhdpi) 70 | 71 | assertTrue destinationLdpi.exists() 72 | assertTrue destinationMdpi.exists() 73 | assertTrue destinationHdpi.exists() 74 | assertTrue destinationXhdpi.exists() 75 | 76 | File expectedLdpi = new File(RESOURCE_PATH, 'relative-ldpi-expected.png') 77 | File expectedMdpi = new File(RESOURCE_PATH, 'relative-mdpi-expected.png') 78 | File expectedHdpi = new File(RESOURCE_PATH, 'relative-hdpi-expected.png') 79 | File expectedXhdpi = new File(RESOURCE_PATH, 'relative-xhdpi-expected.png') 80 | 81 | assertTrue FileUtils.contentEquals(destinationLdpi, expectedLdpi) 82 | assertTrue FileUtils.contentEquals(destinationMdpi, expectedMdpi) 83 | assertTrue FileUtils.contentEquals(destinationHdpi, expectedHdpi) 84 | assertTrue FileUtils.contentEquals(destinationXhdpi, expectedXhdpi) 85 | } 86 | 87 | @Test 88 | void canResizePngWithPixelSize() { 89 | Converter converter = new Converter() 90 | 91 | File svgFile = new File(RESOURCE_PATH, 'pixel.svg') 92 | SVGResource svgResource = new SVGResource(svgFile, 72) 93 | 94 | File destinationLdpi = new File(OUT_PATH, 'pixel-ldpi.png') 95 | converter.transcode(svgResource, Density.LDPI, destinationLdpi) 96 | 97 | File destinationMdpi = new File(OUT_PATH, 'pixel-mdpi.png') 98 | converter.transcode(svgResource, Density.MDPI, destinationMdpi) 99 | 100 | File destinationHdpi = new File(OUT_PATH, 'pixel-hdpi.png') 101 | converter.transcode(svgResource, Density.HDPI, destinationHdpi) 102 | 103 | File destinationXhdpi = new File(OUT_PATH, 'pixel-xhdpi.png') 104 | converter.transcode(svgResource, Density.XHDPI, destinationXhdpi) 105 | 106 | assertTrue destinationLdpi.exists() 107 | assertTrue destinationMdpi.exists() 108 | assertTrue destinationHdpi.exists() 109 | assertTrue destinationXhdpi.exists() 110 | 111 | File expectedLdpi = new File(RESOURCE_PATH, 'pixel-ldpi-expected.png') 112 | File expectedMdpi = new File(RESOURCE_PATH, 'pixel-mdpi-expected.png') 113 | File expectedHdpi = new File(RESOURCE_PATH, 'pixel-hdpi-expected.png') 114 | File expectedXhdpi = new File(RESOURCE_PATH, 'pixel-xhdpi-expected.png') 115 | 116 | assertTrue FileUtils.contentEquals(destinationLdpi, expectedLdpi) 117 | assertTrue FileUtils.contentEquals(destinationMdpi, expectedMdpi) 118 | assertTrue FileUtils.contentEquals(destinationHdpi, expectedHdpi) 119 | assertTrue FileUtils.contentEquals(destinationXhdpi, expectedXhdpi) 120 | } 121 | 122 | @Test 123 | void canRasterizeImageTag() { 124 | Converter converter = new Converter() 125 | 126 | File svgFile = new File(RESOURCE_PATH, 'image-tag.svg') 127 | SVGResource svgResource = new SVGResource(svgFile, 72) 128 | File destination = new File(OUT_PATH, 'image-tag-rasterize.png') 129 | converter.transcode(svgResource, Density.MDPI, destination) 130 | 131 | assertTrue destination.exists() 132 | 133 | File expected = new File(RESOURCE_PATH, 'image-tag-rasterize-expected.png') 134 | boolean isEqual = FileUtils.contentEquals(destination, expected) 135 | if (!isEqual) { 136 | // This *should* be an assertion, but I can't figure out why Travis' build produces 137 | // different PNGs (that are visually identical, but encoded slightly different). 138 | // TODO: Make this test better 139 | System.out.println("Image not what was expected - but different systems render PNGs differently."); 140 | } 141 | } 142 | 143 | @Test 144 | void canRasterizeProblematicSvg() { 145 | Converter converter = new Converter() 146 | 147 | File svgFile = new File(RESOURCE_PATH, 'problematic.svg') 148 | SVGResource svgResource = new SVGResource(svgFile, 72) 149 | File destination = new File(OUT_PATH, 'problematic-rasterize.png') 150 | converter.transcode(svgResource, Density.MDPI, destination) 151 | 152 | assertTrue destination.exists() 153 | 154 | File expected = new File(RESOURCE_PATH, 'problematic-rasterize-expected.png') 155 | assertTrue FileUtils.contentEquals(destination, expected) 156 | } 157 | 158 | @Test 159 | void ignoresNonexistantFiles() { 160 | Converter converter = new Converter() 161 | 162 | File svgFile = new File('does-not-exist.svg') 163 | SVGResource svgResource = new SVGResource(svgFile, 72) 164 | File destination = new File(OUT_PATH, 'does-not-exist.png') 165 | converter.transcode(svgResource, Density.MDPI, destination) 166 | 167 | // Assert that we *didn't* create a file for this! 168 | assertFalse destination.exists() 169 | } 170 | 171 | @Test 172 | void ignoreCompletelyInvalidSvg() { 173 | Converter converter = new Converter() 174 | 175 | File svgFile = new File(RESOURCE_PATH, 'invalid.svg') 176 | SVGResource svgResource = new SVGResource(svgFile, 72) 177 | File destination = new File(OUT_PATH, 'invalid.png') 178 | converter.transcode(svgResource, Density.MDPI, destination) 179 | 180 | // Assert that we *didn't* create a file for this! 181 | assertFalse destination.exists() 182 | } 183 | 184 | @Test 185 | void ignoreSomewhatInvalidSvg() { 186 | Converter converter = new Converter() 187 | 188 | File svgFile = new File(RESOURCE_PATH, 'invalid2.svg') 189 | SVGResource svgResource = new SVGResource(svgFile, 72) 190 | File destination = new File(OUT_PATH, 'invalid2.png') 191 | converter.transcode(svgResource, Density.MDPI, destination) 192 | 193 | // Assert that we *didn't* create a file for this! 194 | assertFalse destination.exists() 195 | } 196 | } 197 | -------------------------------------------------------------------------------- /victor/src/main/java/org/apache/batik/ext/awt/image/codec/imageio/ImageIOImageWriter.java: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Licensed to the Apache Software Foundation (ASF) under one or more 4 | contributor license agreements. See the NOTICE file distributed with 5 | this work for additional information regarding copyright ownership. 6 | The ASF licenses this file to You under the Apache License, Version 2.0 7 | (the "License"); you may not use this file except in compliance with 8 | the License. You may obtain a copy of the License at 9 | 10 | http://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 | package org.apache.batik.ext.awt.image.codec.imageio; 20 | 21 | import java.awt.image.RenderedImage; 22 | import java.io.IOException; 23 | import java.io.OutputStream; 24 | import java.util.Iterator; 25 | 26 | import javax.imageio.IIOImage; 27 | import javax.imageio.ImageIO; 28 | import javax.imageio.ImageTypeSpecifier; 29 | import javax.imageio.ImageWriteParam; 30 | import javax.imageio.event.IIOWriteWarningListener; 31 | import javax.imageio.metadata.IIOInvalidTreeException; 32 | import javax.imageio.metadata.IIOMetadata; 33 | import javax.imageio.metadata.IIOMetadataNode; 34 | import javax.imageio.stream.ImageOutputStream; 35 | 36 | import org.w3c.dom.Node; 37 | import org.w3c.dom.NodeList; 38 | 39 | import org.apache.batik.ext.awt.image.spi.ImageWriter; 40 | import org.apache.batik.ext.awt.image.spi.ImageWriterParams; 41 | 42 | /** 43 | * ImageWriter implementation that uses Image I/O to write images. 44 | * 45 | * @version $Id$ 46 | */ 47 | public class ImageIOImageWriter implements ImageWriter, IIOWriteWarningListener { 48 | 49 | private String targetMIME; 50 | 51 | /** 52 | * Main constructor. 53 | * @param mime the MIME type of the image format 54 | */ 55 | public ImageIOImageWriter(String mime) { 56 | this.targetMIME = mime; 57 | } 58 | 59 | /** 60 | * @see ImageWriter#writeImage(RenderedImage, OutputStream) 61 | */ 62 | public void writeImage(RenderedImage image, OutputStream out) throws IOException { 63 | writeImage(image, out, null); 64 | } 65 | 66 | /** 67 | * @see ImageWriter#writeImage(RenderedImage, OutputStream, ImageWriterParams) 68 | */ 69 | public void writeImage(RenderedImage image, OutputStream out, 70 | ImageWriterParams params) 71 | throws IOException { 72 | Iterator iter; 73 | iter = ImageIO.getImageWritersByMIMEType(getMIMEType()); 74 | javax.imageio.ImageWriter iiowriter = null; 75 | try { 76 | iiowriter = (javax.imageio.ImageWriter)iter.next(); 77 | if (iiowriter != null) { 78 | iiowriter.addIIOWriteWarningListener(this); 79 | 80 | ImageOutputStream imgout = null; 81 | try { 82 | imgout = ImageIO.createImageOutputStream(out); 83 | ImageWriteParam iwParam = getDefaultWriteParam(iiowriter, image, params); 84 | 85 | ImageTypeSpecifier type; 86 | if (iwParam.getDestinationType() != null) { 87 | type = iwParam.getDestinationType(); 88 | } else { 89 | type = ImageTypeSpecifier.createFromRenderedImage(image); 90 | } 91 | 92 | //Handle metadata 93 | IIOMetadata meta = iiowriter.getDefaultImageMetadata( 94 | type, iwParam); 95 | //meta might be null for some JAI codecs as they don't support metadata 96 | if (params != null && meta != null) { 97 | meta = updateMetadata(meta, params); 98 | } 99 | 100 | //Write image 101 | iiowriter.setOutput(imgout); 102 | IIOImage iioimg = new IIOImage(image, null, meta); 103 | iiowriter.write(null, iioimg, iwParam); 104 | } finally { 105 | if (imgout != null) { 106 | imgout.close(); 107 | } 108 | } 109 | } else { 110 | throw new UnsupportedOperationException("No ImageIO codec for writing " 111 | + getMIMEType() + " is available!"); 112 | } 113 | } finally { 114 | if (iiowriter != null) { 115 | iiowriter.dispose(); 116 | } 117 | } 118 | } 119 | 120 | /** 121 | * Returns the default write parameters for encoding the image. 122 | * @param iiowriter The IIO ImageWriter that will be used 123 | * @param image the image to be encoded 124 | * @param params the parameters for this writer instance 125 | * @return the IIO ImageWriteParam instance 126 | */ 127 | protected ImageWriteParam getDefaultWriteParam( 128 | javax.imageio.ImageWriter iiowriter, RenderedImage image, 129 | ImageWriterParams params) { 130 | ImageWriteParam param = iiowriter.getDefaultWriteParam(); 131 | if ((params != null) && (params.getCompressionMethod() != null)) { 132 | param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); 133 | param.setCompressionType(params.getCompressionMethod()); 134 | } 135 | return param; 136 | } 137 | 138 | /** 139 | * Updates the metadata information based on the parameters to this writer. 140 | * @param meta the metadata 141 | * @param params the parameters 142 | * @return the updated metadata 143 | */ 144 | protected IIOMetadata updateMetadata(IIOMetadata meta, ImageWriterParams params) { 145 | final String stdmeta = "javax_imageio_1.0"; 146 | if (meta.isStandardMetadataFormatSupported()) { 147 | IIOMetadataNode root = (IIOMetadataNode)meta.getAsTree(stdmeta); 148 | IIOMetadataNode dim = getChildNode(root, "Dimension"); 149 | IIOMetadataNode child; 150 | if (params.getResolution() != null) { 151 | child = getChildNode(dim, "HorizontalPixelSize"); 152 | if (child == null) { 153 | child = new IIOMetadataNode("HorizontalPixelSize"); 154 | dim.appendChild(child); 155 | } 156 | child.setAttribute("value", 157 | Double.toString(params.getResolution().doubleValue() / 25.4)); 158 | child = getChildNode(dim, "VerticalPixelSize"); 159 | if (child == null) { 160 | child = new IIOMetadataNode("VerticalPixelSize"); 161 | dim.appendChild(child); 162 | } 163 | child.setAttribute("value", 164 | Double.toString(params.getResolution().doubleValue() / 25.4)); 165 | } 166 | try { 167 | meta.mergeTree(stdmeta, root); 168 | } catch (IIOInvalidTreeException e) { 169 | throw new RuntimeException("Cannot update image metadata: " 170 | + e.getMessage()); 171 | } 172 | } 173 | return meta; 174 | } 175 | 176 | /** 177 | * Returns a specific metadata child node 178 | * @param n the base node 179 | * @param name the name of the child 180 | * @return the requested child node 181 | */ 182 | protected static IIOMetadataNode getChildNode(Node n, String name) { 183 | NodeList nodes = n.getChildNodes(); 184 | for (int i = 0; i < nodes.getLength(); i++) { 185 | Node child = nodes.item(i); 186 | if (name.equals(child.getNodeName())) { 187 | return (IIOMetadataNode)child; 188 | } 189 | } 190 | return null; 191 | } 192 | 193 | /** 194 | * @see ImageWriter#getMIMEType() 195 | */ 196 | public String getMIMEType() { 197 | return this.targetMIME; 198 | } 199 | 200 | /** 201 | * @see IIOWriteWarningListener#warningOccurred(javax.imageio.ImageWriter, int, String) 202 | */ 203 | public void warningOccurred(javax.imageio.ImageWriter source, 204 | int imageIndex, String warning) { 205 | System.err.println("Problem while writing image using ImageI/O: " 206 | + warning); 207 | } 208 | } 209 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | --------------------------------------------------------------------------------