diff src/name/blackcap/imageprep/RotateDialog.kt @ 12:26a507e095ab

Use ImageObserver and wait if needed.
author David Barts <n5jrn@me.com>
date Sat, 18 Jul 2020 12:04:05 -0700
parents 1f824742e1fa
children 3feeb953d9ae
line wrap: on
line diff
--- a/src/name/blackcap/imageprep/RotateDialog.kt	Sat Jul 18 08:12:00 2020 -0700
+++ b/src/name/blackcap/imageprep/RotateDialog.kt	Sat Jul 18 12:04:05 2020 -0700
@@ -6,11 +6,14 @@
 import java.awt.Dimension
 import java.awt.Graphics
 import java.awt.Graphics2D
+import java.awt.Image
 import java.awt.Toolkit
 import java.awt.event.ActionListener
 import java.awt.image.BufferedImage
+import java.awt.image.ImageObserver
 import java.io.File
 import java.io.IOException
+import java.util.concurrent.Semaphore
 import java.util.logging.Level
 import java.util.logging.Logger
 import javax.imageio.ImageIO
@@ -41,6 +44,26 @@
     }
     private val drawingPane = DrawingPane(initialImage)
 
+    private class ImageWaiter: ImageObserver {
+        private var sem = Semaphore(0)
+        @Volatile private var flags: Int? = null
+        private var MASK = ImageObserver.ALLBITS or ImageObserver.ERROR or ImageObserver.ABORT
+
+        override fun imageUpdate(img: Image, infoflags: Int, x: Int, y: Int, width: Int, height: Int): Boolean {
+            if (infoflags and MASK != 0) {
+                flags = infoflags
+                sem.release()
+                return false
+            }
+            return true
+        }
+
+        fun wait(): Int {
+            sem.acquire()
+            return flags!!
+        }
+    }
+
     val image: BufferedImage
     get() { return drawingPane.image }
 
@@ -131,7 +154,9 @@
                             val nHeight = (imageIn.height * ratio).toInt()
                             val imageOut = BufferedImage(nWidth, nHeight, imageIn.type)
                             imageOut.createGraphics().run {
-                                drawImage(imageIn.getScaledInstance(nWidth, nHeight, BufferedImage.SCALE_SMOOTH), 0, 0, null)
+                                val w = ImageWaiter()
+                                if (!drawImage(imageIn.getScaledInstance(nWidth, nHeight, BufferedImage.SCALE_SMOOTH), 0, 0, w))
+                                    w.wait()
                                 dispose()
                             }
                             Pair(imageOut, null)