Java 9 Multi-Resolution Image API
Java 9 defines the multi-resolution image API, so developers can easily manipulate and display images of different resolutions.
The following are the main operations of the multi-resolution image API:
-
Image getResolutionVariant(double destImageWidth, double destImageHeight) − Gets an image variant for a specific resolution - represents a logical image of a specific size at a known resolution in DPI, and this image is the best variant..
-
List
getResolutionVariants() − Returns a list of image variants with readable resolutions.
Example
import
java
.
io
.
IOException
;
import
java
.
net
.
URL
;
import
java
.
net
.
MalformedURLException
;
import
java
.
util
.
ArrayList
;
import
java
.
util
.
List
;
import
java
.
awt
.
Image
;
import
java
.
awt
.
image
.
MultiResolutionImage
;
import
java
.
awt
.
image
.
BaseMultiResolutionImage
;
import
javax
.
imageio
.
ImageIO
;
public
class
Tester
{
public
static
void
main
(
String
[
]
args
)
throws
IOException
,
MalformedURLException
{
List
<
String
imgUrls
=
List.
of
(
"
http://www.runoob.com/wp-content/themes/runoob/assets/img/runoob-logo@2x.png
"
,
"
http://www.runoob.com/wp-content/themes/runoob/assets/img/runoob-logo.png
"
,
"
http://www.runoob.com/wp-content/themes/runoob/assets/images/qrcode.png
"
)
;
List
<
Image
images
=
new
ArrayList
<
Image
(
);
for
(
String
url
:
imgUrls
)
{
images
.
add
(
ImageIO
.
read
(
new
URL
(
url
)
)
)
;
}
//
Read all images
MultiResolutionImage
multiResolutionImage
=
new
BaseMultiResolutionImage
(
images
.
toArray
(
new
Image
[
0
]
)
)
;
//
Get all resolutions of the image
List
<
Image
variants
=
multiResolutionImage.
getResolutionVariants
(
)
;
System
.
out
.
println
(
"
Total number of images:
"
variants
.
size
(
)
)
;
for
(
Image
img
:
variants
)
{
System
.
out
.
println
(
img
)
;
}
//
Get the corresponding image resolution based on different sizes
Image
variant1
=
multiResolutionImage
.
getResolutionVariant
(
156
,
45
)
;
System
.
out
.
printf
(
"
\n
Image for destination[%d,%d]: [%d,%d]
"
,
156
,
45
,
variant1
.
getWidth
(
null
)
,
variant1
.
getHeight
(
null
)
)
;
Image
variant2
=
multiResolutionImage
.
getResolutionVariant
(
311
,
89
)
;
System
.
out
.
printf
(
"
\n
Image for destination[%d,%d]: [%d,%d]
"
,
311
,
89
,
variant2
.
getWidth
(
null
)
,
variant2
.
getHeight
(
null
)
)
;
Image
variant3
=
multiResolutionImage
.
getResolutionVariant
(
622
,
178
)
;
System
.
out
.
printf
(
"
\n
Image for destination[%d,%d]: [%d,%d]
"
,
622
,
178
,
variant3
.
getWidth
(
null
)
,
variant3
.
getHeight
(
null
)
)
;
Image
variant4
=
multiResolutionImage
.
getResolutionVariant
(
300
,
300
)
;
System
.
out
.
printf
(
"
\n
Image for destination[%d,%d]: [%d,%d]
"
,
300
,
300
,
variant4
.
getWidth
(
null
)
,
variant4
.
getHeight
(
null
)
)
;
}
}
Java 9 New Features