Advertisement
Guest User

Untitled

a guest
Jun 19th, 2017
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.73 KB | None | 0 0
  1. package com.voyageone.components.s7.template.analysis.viewer
  2.  
  3. import java.awt.image.BufferedImage
  4. import java.io.ByteArrayInputStream
  5. import java.io.ByteArrayOutputStream
  6. import java.io.InputStream
  7. import javax.imageio.ImageIO
  8.  
  9. fun adaptiveCenterAsStream(imageInputStream: InputStream, size: String): InputStream = adaptiveCenterAsImage(imageInputStream, size).let {
  10. val os = ByteArrayOutputStream()
  11. ImageIO.write(it, "png", os)
  12. return ByteArrayInputStream(os.toByteArray())
  13. }
  14.  
  15. fun adaptiveCenterAsImage(imageInputStream: InputStream, size: String): BufferedImage = SizeHelper(size).let {
  16. return adaptiveCenterAsImage(imageInputStream, it)
  17. }
  18.  
  19. fun adaptiveCenterAsImage(imageInputStream: InputStream, size: SizeHelper): BufferedImage = ImageIO.read(imageInputStream).let {
  20. return adaptiveCenter(it, size.width, size.height)
  21. }
  22.  
  23. /**
  24. * 自适应居中图片到目标大小的画布上
  25. */
  26. fun adaptiveCenter(image: BufferedImage, newWidth: Double, newHeight: Double): BufferedImage {
  27. val bufferedWidth = newWidth
  28. val bufferedHeight = newHeight
  29. val widthScale = bufferedWidth / image.width
  30. val heightScale = bufferedHeight / image.height
  31. val width: Double
  32. val height: Double
  33. val x: Double
  34. val y: Double
  35.  
  36. when {
  37. widthScale >= 1 && heightScale >= 1 -> {
  38. // 图片和画布都是等比,并且图片小于画布
  39. // 则不需要处理,直接居中即可
  40. width = image.width.toDouble()
  41. height = image.height.toDouble()
  42. x = (bufferedWidth - width) / 2
  43. y = (bufferedHeight - height) / 2
  44. }
  45. widthScale > heightScale -> {
  46. // 图片比画布稍大
  47. // 并且高度的缩放幅度大于宽度的
  48. // 所以按高度比例进行缩放
  49. width = image.width * heightScale
  50. height = bufferedHeight
  51. x = (bufferedWidth - width) / 2
  52. y = 0.0
  53. }
  54. widthScale < heightScale -> {
  55. // 图片比画布稍大
  56. // 并且宽度的缩放幅度大于高度的
  57. // 所以按宽度比例进行缩放
  58. width = bufferedWidth
  59. height = image.height * widthScale
  60. x = 0.0
  61. y = (bufferedHeight - height) / 2
  62. }
  63. else -> {
  64. // 图片比画布大
  65. // 并且两边比例相同
  66. width = bufferedWidth
  67. height = bufferedHeight
  68. x = 0.0
  69. y = 0.0
  70. }
  71. }
  72.  
  73. val bufferedImage = BufferedImage(bufferedWidth.toInt(), bufferedHeight.toInt(), BufferedImage.TYPE_INT_ARGB)
  74. val g2d = bufferedImage.graphics
  75. g2d.drawImage(image, x.toInt(), y.toInt(), width.toInt(), height.toInt(), null)
  76. g2d.dispose()
  77. return bufferedImage
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement