Loading...
Searching...
No Matches
BitmapRegionDecoderExample.kt
Go to the documentation of this file.
1import kotlinx.coroutines.delay
2import kotlinx.coroutines.runBlocking
3
4/**
5 * BitmapRegionDecoder usage example for Kotlin
6 * Demonstrates working with bitmap region decoding, image processing, and rectangle operations
7 */
8class BitmapRegionDecoderExample {
9 private var decoder: BitmapRegionDecoder? = null
10 private var imageData: ByteArray? = null
11
12 init {
13 loadSampleImageData()
14 }
15
16 /**
17 * Load sample image data for demonstration
18 */
19 private fun loadSampleImageData() {
20 // Simulate loading image data (in real app, this would be from file or network)
21 imageData = byteArrayOf(
22 0x89.toByte(), 0x50.toByte(), 0x4E.toByte(), 0x47.toByte(),
23 0x0D.toByte(), 0x0A.toByte(), 0x1A.toByte(), 0x0A.toByte() // PNG header
24 // ... more image data would be here
25 )
26 println("Sample image data loaded (${imageData!!.size} bytes)")
27 }
28
29 /**
30 * Demonstrate BitmapRegionDecoder methods
31 */
32 fun demonstrateBitmapRegionDecoderMethods() {
33 if (imageData == null) {
34 System.err.println("No image data available")
35 return
36 }
37
38 // [kotlin_BitmapRegionDecoder_newInstance]
39 // Create new instance of BitmapRegionDecoder
40 decoder = BitmapRegionDecoder.newInstance(imageData!!)
41 println("Created BitmapRegionDecoder instance")
42 // [kotlin_BitmapRegionDecoder_newInstance]
43
44 // Demonstrate rectangle creation and usage
45 demonstrateRectangleUsage()
46
47 // Demonstrate region decoding
48 demonstrateRegionDecoding()
49
50 // Demonstrate different sample sizes
51 demonstrateSampleSizes()
52
53 // Demonstrate multiple regions
54 demonstrateMultipleRegions()
55 }
56
57 /**
58 * Demonstrate Rectangle usage
59 */
60 fun demonstrateRectangleUsage() {
61 // [kotlin_Rectangle_constructor]
62 // Create rectangle with x, y, width, height
63 val rect1 = Rectangle(10, 20, 100, 150)
64 println("Created rectangle: x=${rect1.x}, y=${rect1.y}, width=${rect1.width}, height=${rect1.height}")
65 // [kotlin_Rectangle_constructor]
66
67 // [kotlin_Rectangle_getX]
68 // Get X coordinate
69 val x = rect1.x
70 println("Rectangle X coordinate: $x")
71 // [kotlin_Rectangle_getX]
72
73 // [kotlin_Rectangle_getY]
74 // Get Y coordinate
75 val y = rect1.y
76 println("Rectangle Y coordinate: $y")
77 // [kotlin_Rectangle_getY]
78
79 // [kotlin_Rectangle_getWidth]
80 // Get width
81 val width = rect1.width
82 println("Rectangle width: $width")
83 // [kotlin_Rectangle_getWidth]
84
85 // [kotlin_Rectangle_getHeight]
86 // Get height
87 val height = rect1.height
88 println("Rectangle height: $height")
89 // [kotlin_Rectangle_getHeight]
90
91 // Create different rectangles for different use cases
92 val fullImage = Rectangle(0, 0, 1024, 768)
93 val topLeft = Rectangle(0, 0, 512, 384)
94 val center = Rectangle(256, 192, 512, 384)
95 val bottomRight = Rectangle(512, 384, 512, 384)
96
97 println("Created different rectangles for different regions")
98 }
99
100 /**
101 * Demonstrate region decoding
102 */
103 fun demonstrateRegionDecoding() {
104 val decoder = decoder ?: run {
105 System.err.println("Decoder not initialized")
106 return
107 }
108
109 // Create a sample rectangle
110 val sampleRect = Rectangle(50, 50, 200, 200)
111
112 // [kotlin_BitmapRegionDecoder_decodeRegion]
113 // Decode region with sample size 1 (full resolution)
114 val decodedImage = decoder.decodeRegion(sampleRect, 1)
115 println("Decoded region: ${sampleRect.width}x${sampleRect.height} at sample size 1")
116 // [kotlin_BitmapRegionDecoder_decodeRegion]
117
118 // Demonstrate the decoded image
119 demonstrateDecodedImage(decodedImage, "Sample Region")
120 }
121
122 /**
123 * Demonstrate different sample sizes
124 */
125 fun demonstrateSampleSizes() {
126 val decoder = decoder ?: return
127
128 val testRect = Rectangle(0, 0, 400, 300)
129
130 // Decode with different sample sizes
131 val sampleSizes = listOf(1.0f, 2.0f, 4.0f, 8.0f)
132
133 for (sampleSize in sampleSizes) {
134 // [kotlin_BitmapRegionDecoder_decodeRegion_sampleSize]
135 // Decode region with specific sample size
136 val decodedImage = decoder.decodeRegion(testRect, sampleSize)
137 println("Decoded region with sample size $sampleSize: ${(testRect.width / sampleSize).toInt()}x${(testRect.height / sampleSize).toInt()}")
138 // [kotlin_BitmapRegionDecoder_decodeRegion_sampleSize]
139
140 demonstrateDecodedImage(decodedImage, "Sample Size $sampleSize")
141 }
142 }
143
144 /**
145 * Demonstrate multiple regions
146 */
147 fun demonstrateMultipleRegions() {
148 val decoder = decoder ?: return
149
150 // Define multiple regions to decode
151 val regions = listOf(
152 Rectangle(0, 0, 256, 256), // Top-left quadrant
153 Rectangle(256, 0, 256, 256), // Top-right quadrant
154 Rectangle(0, 256, 256, 256), // Bottom-left quadrant
155 Rectangle(256, 256, 256, 256) // Bottom-right quadrant
156 )
157
158 println("=== Decoding Multiple Regions ===")
159 for (i in regions.indices) {
160 val region = regions[i]
161
162 // [kotlin_BitmapRegionDecoder_decodeRegion_multiple]
163 // Decode multiple regions
164 val decodedImage = decoder.decodeRegion(region, 1)
165 println("Region ${i + 1}: ${region.width}x${region.height} at (${region.x}, ${region.y})")
166 // [kotlin_BitmapRegionDecoder_decodeRegion_multiple]
167
168 demonstrateDecodedImage(decodedImage, "Region ${i + 1}")
169 }
170 }
171
172 /**
173 * Demonstrate decoded image usage
174 */
175 fun demonstrateDecodedImage(image: ImageWrapper, description: String) {
176 println("--- $description ---")
177 println("Image dimensions: ${image.width}x${image.height}")
178 println("Image format: ${image.format}")
179 println("Image data size: ${image.data.size} bytes")
180 println("---")
181 }
182
183 /**
184 * Demonstrate advanced bitmap region decoder features
185 */
186 suspend fun demonstrateAdvancedFeatures() {
187 println("=== Advanced BitmapRegionDecoder Features ===")
188
189 if (imageData == null) {
190 return
191 }
192
193 // Create multiple decoders for different images
194 val imageDataList = listOf(
195 imageData!!,
196 byteArrayOf(0xFF.toByte(), 0xD8.toByte(), 0xFF.toByte(), 0xE0.toByte()), // JPEG header
197 byteArrayOf(0x47.toByte(), 0x49.toByte(), 0x46.toByte(), 0x38.toByte()) // GIF header
198 )
199
200 for (i in imageDataList.indices) {
201 try {
202 // [kotlin_BitmapRegionDecoder_newInstance_advanced]
203 // Create decoder for different image types
204 val decoder = BitmapRegionDecoder.newInstance(imageDataList[i])
205 println("Created decoder for image type ${i + 1}")
206 // [kotlin_BitmapRegionDecoder_newInstance_advanced]
207
208 // Test decoding with different regions
209 val testRect = Rectangle(0, 0, 100, 100)
210 val decodedImage = decoder.decodeRegion(testRect, 1)
211 println("Successfully decoded region from image type ${i + 1}")
212
213 } catch (e: Exception) {
214 System.err.println("Failed to decode image type ${i + 1}: ${e.message}")
215 }
216 }
217 }
218
219 /**
220 * Demonstrate error handling
221 */
222 fun demonstrateErrorHandling() {
223 println("=== Error Handling ===")
224
225 // Test with invalid image data
226 val invalidData = byteArrayOf(0x00.toByte(), 0x01.toByte(), 0x02.toByte(), 0x03.toByte())
227
228 try {
229 // [kotlin_BitmapRegionDecoder_newInstance_error]
230 // Create decoder with invalid data
231 val decoder = BitmapRegionDecoder.newInstance(invalidData)
232 println("Created decoder with invalid data")
233 // [kotlin_BitmapRegionDecoder_newInstance_error]
234
235 // Try to decode region
236 val rect = Rectangle(0, 0, 50, 50)
237 val image = decoder.decodeRegion(rect, 1)
238 println("Successfully decoded region from invalid data")
239
240 } catch (e: Exception) {
241 println("Expected error when creating decoder with invalid data: ${e.message}")
242 }
243
244 // Test with invalid rectangle
245 decoder?.let { decoder ->
246 try {
247 val invalidRect = Rectangle(-10, -10, 100, 100)
248 val image = decoder.decodeRegion(invalidRect, 1)
249 println("Successfully decoded region with negative coordinates")
250
251 } catch (e: Exception) {
252 println("Expected error with invalid rectangle: ${e.message}")
253 }
254 }
255 }
256
257 /**
258 * Demonstrate performance optimization
259 */
260 fun demonstratePerformanceOptimization() {
261 println("=== Performance Optimization ===")
262
263 val decoder = decoder ?: return
264
265 // Test different sample sizes for performance
266 val largeRect = Rectangle(0, 0, 800, 600)
267 val sampleSizes = listOf(1.0f, 2.0f, 4.0f, 8.0f, 16.0f)
268
269 for (sampleSize in sampleSizes) {
270 val startTime = System.currentTimeMillis()
271
272 val image = decoder.decodeRegion(largeRect, sampleSize)
273
274 val endTime = System.currentTimeMillis()
275 println("Sample size $sampleSize: ${endTime - startTime}ms, " +
276 "Output size: ${image.width}x${image.height}")
277 }
278 }
279
280 /**
281 * Demonstrate rectangle manipulation
282 */
283 fun demonstrateRectangleManipulation() {
284 println("=== Rectangle Manipulation ===")
285
286 // Create base rectangle
287 val baseRect = Rectangle(100, 100, 200, 150)
288 println("Base rectangle: ${baseRect.x}, ${baseRect.y}, ${baseRect.width}x${baseRect.height}")
289
290 // Create different variations
291 val variations = listOf(
292 Rectangle(baseRect.x, baseRect.y, baseRect.width / 2, baseRect.height), // Half width
293 Rectangle(baseRect.x, baseRect.y, baseRect.width, baseRect.height / 2), // Half height
294 Rectangle(baseRect.x + 50, baseRect.y + 25, baseRect.width - 100, baseRect.height - 50), // Centered smaller
295 Rectangle(0, 0, baseRect.width, baseRect.height) // Top-left aligned
296 )
297
298 for (i in variations.indices) {
299 val rect = variations[i]
300 println("Variation ${i + 1}: ${rect.x}, ${rect.y}, ${rect.width}x${rect.height}")
301 }
302 }
303
304 /**
305 * Main demonstration method
306 */
307 suspend fun runExample() {
308 println("=== BitmapRegionDecoder Example ===")
309
310 demonstrateBitmapRegionDecoderMethods()
311 demonstrateRectangleManipulation()
312 demonstrateAdvancedFeatures()
313 demonstrateErrorHandling()
314 demonstratePerformanceOptimization()
315
316 // Wait a bit for processing
317 delay(2000)
318
319 println("=== Example completed ===")
320 }
321}
322
323/**
324 * Function to run the example
325 */
326fun main() = runBlocking {
327 val example = BitmapRegionDecoderExample()
328 example.runExample()
329}