Last active
June 19, 2017 10:47
-
-
Save JonasGao/36353215eea801260d973c828512e0c2 to your computer and use it in GitHub Desktop.
Adaptive centering picture (Based on Java. Writing with Kotlin)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.voyageone.components.s7.template.analysis.viewer | |
import java.awt.image.BufferedImage | |
import java.io.ByteArrayInputStream | |
import java.io.ByteArrayOutputStream | |
import java.io.InputStream | |
import javax.imageio.ImageIO | |
fun adaptiveCenterAsStream(imageInputStream: InputStream, size: String): InputStream = adaptiveCenterAsImage(imageInputStream, size).let { | |
val os = ByteArrayOutputStream() | |
ImageIO.write(it, "png", os) | |
return ByteArrayInputStream(os.toByteArray()) | |
} | |
fun adaptiveCenterAsImage(imageInputStream: InputStream, size: String): BufferedImage = SizeHelper(size).let { | |
return adaptiveCenterAsImage(imageInputStream, it) | |
} | |
fun adaptiveCenterAsImage(imageInputStream: InputStream, size: SizeHelper): BufferedImage = ImageIO.read(imageInputStream).let { | |
return adaptiveCenter(it, size.width, size.height) | |
} | |
/** | |
* 自适应居中图片到目标大小的画布上 | |
*/ | |
fun adaptiveCenter(image: BufferedImage, newWidth: Double, newHeight: Double): BufferedImage { | |
val bufferedWidth = newWidth | |
val bufferedHeight = newHeight | |
val widthScale = bufferedWidth / image.width | |
val heightScale = bufferedHeight / image.height | |
val width: Double | |
val height: Double | |
val x: Double | |
val y: Double | |
when { | |
widthScale >= 1 && heightScale >= 1 -> { | |
// 图片和画布都是等比,并且图片小于画布 | |
// 则不需要处理,直接居中即可 | |
width = image.width.toDouble() | |
height = image.height.toDouble() | |
x = (bufferedWidth - width) / 2 | |
y = (bufferedHeight - height) / 2 | |
} | |
widthScale > heightScale -> { | |
// 图片比画布稍大 | |
// 并且高度的缩放幅度大于宽度的 | |
// 所以按高度比例进行缩放 | |
width = image.width * heightScale | |
height = bufferedHeight | |
x = (bufferedWidth - width) / 2 | |
y = 0.0 | |
} | |
widthScale < heightScale -> { | |
// 图片比画布稍大 | |
// 并且宽度的缩放幅度大于高度的 | |
// 所以按宽度比例进行缩放 | |
width = bufferedWidth | |
height = image.height * widthScale | |
x = 0.0 | |
y = (bufferedHeight - height) / 2 | |
} | |
else -> { | |
// 图片比画布大 | |
// 并且两边比例相同 | |
width = bufferedWidth | |
height = bufferedHeight | |
x = 0.0 | |
y = 0.0 | |
} | |
} | |
val bufferedImage = BufferedImage(bufferedWidth.toInt(), bufferedHeight.toInt(), BufferedImage.TYPE_INT_ARGB) | |
val g2d = bufferedImage.graphics | |
g2d.drawImage(image, x.toInt(), y.toInt(), width.toInt(), height.toInt(), null) | |
g2d.dispose() | |
return bufferedImage | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment