如何保存旋转后的图片?点击按钮旋转90度存入SQLite仍为原图
Hey there! I get exactly what's going on here—you're rotating the image on screen just fine, but when you save it to SQLite, it's still the original unrotated version. That's super common because most UI-level rotations only change how the image is displayed, not the underlying image data itself. Let's fix this step by step:
Step 1: Rotate the actual Bitmap data (not just the UI)
When you use something like imageView.rotation = 90f, you're just telling the system to draw the image at an angle—but the original Bitmap object behind it stays the same. Instead, you need to create a new rotated Bitmap every time the button is clicked:
// Keep a variable to track the current rotation angle (start at 0) private var currentRotation = 0f // Inside your button click listener buttonRotate.setOnClickListener { currentRotation += 90f // Get the original Bitmap from the ImageView val originalBitmap = (imageView.drawable as BitmapDrawable).bitmap // Create a matrix to apply the rotation transformation val matrix = Matrix() matrix.postRotate(currentRotation) // Generate the new rotated Bitmap val rotatedBitmap = Bitmap.createBitmap( originalBitmap, 0, 0, originalBitmap.width, originalBitmap.height, matrix, true // Enable filtering for smoother rotated edges ) // Update the ImageView to show the rotated Bitmap imageView.setImageBitmap(rotatedBitmap) // Clean up the old Bitmap to avoid memory leaks if (!originalBitmap.isRecycled) { originalBitmap.recycle() } }
Step 2: Convert the rotated Bitmap to ByteArray for SQLite
Now that you have the actual rotated Bitmap, convert it to a ByteArray just like you did before—but use the new rotatedBitmap instead of the original:
fun convertBitmapToByteArray(bitmap: Bitmap): ByteArray { val outputStream = ByteArrayOutputStream() bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream) return outputStream.toByteArray() } // When saving to SQLite: val rotatedImageData = convertBitmapToByteArray(rotatedBitmap) // Insert rotatedImageData into your SQLite database table here
Key Notes to Avoid Headaches
- Track rotation state: Using a
currentRotationvariable ensures each click adds another 90 degrees instead of resetting to 90 every time. - Memory management: Always recycle old Bitmaps after creating new ones—Bitmap objects are memory-heavy, and this prevents leaks in long-running apps.
- If using image loaders (like Glide): If you're loading images from files/URLs with a library, make sure you retrieve the raw Bitmap from the loader first before applying rotation, instead of just modifying the ImageView's rotation property.
That should do it! Now when you save to SQLite, you'll be storing the fully rotated image data instead of the original unmodified version.
内容的提问来源于stack exchange,提问作者Scooltr

