XML文件
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#262626"
tools:context=".MainActivity">
<android.opengl.GLSurfaceView
android:id="@+id/glSurfaceView"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toTopOf="@id/tvInfo"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/tvInfo"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:ellipsize="end"
android:maxLines="3"
android:padding="12dp"
android:text="点击「加载图片」选择一张图片"
android:textColor="#CCCCCC"
android:textSize="13sp"
app:layout_constraintBottom_toTopOf="@id/btnLoad"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<Button
android:id="@+id/btnLoad"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginBottom="12dp"
android:layout_marginEnd="6dp"
android:layout_marginStart="12dp"
android:text="加载图片"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="@id/btnExport"
app:layout_constraintStart_toStartOf="parent" />
<Button
android:id="@+id/btnExport"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginBottom="12dp"
android:layout_marginEnd="12dp"
android:layout_marginStart="6dp"
android:text="导出图片"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="@id/btnLoad" />
</androidx.constraintlayout.widget.ConstraintLayout>
Activity代码
package com.example.phototurbodemo
import android.content.ContentValues
import android.content.Intent
import android.graphics.BitmapFactory
import android.net.Uri
import android.opengl.GLSurfaceView
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.os.Trace
import android.provider.MediaStore
import android.util.Log
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
class MainActivity : AppCompatActivity() {
companion object {
private const val TAG = "yang"
}
private lateinit var glSurfaceView: GLSurfaceView
private lateinit var renderer: TextureRenderer
private lateinit var tvInfo: TextView
private var loadedFilePath: String? = null
private val pickImage = registerForActivityResult(ActivityResultContracts.GetContent()) { uri: Uri? ->
uri?.let { onImagePicked(it) }
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContentView(R.layout.activity_main)
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
insets
}
tvInfo = findViewById(R.id.tvInfo)
renderer = TextureRenderer()
glSurfaceView = findViewById(R.id.glSurfaceView)
glSurfaceView.setEGLContextClientVersion(3)
glSurfaceView.setRenderer(renderer)
glSurfaceView.renderMode = GLSurfaceView.RENDERMODE_WHEN_DIRTY
findViewById<Button>(R.id.btnLoad).setOnClickListener {
pickImage.launch("image
private fun onImagePicked(uri: Uri) {
try {
val inputDir = File(filesDir, "input")
inputDir.mkdirs()
val localFile = File(inputDir, "source_image.png")
contentResolver.openInputStream(uri)?.use { input ->
FileOutputStream(localFile).use { output ->
input.copyTo(output)
}
} ?: run {
Toast.makeText(this, "无法读取图片", Toast.LENGTH_SHORT).show()
return
}
val filePath = localFile.absolutePath
loadedFilePath = filePath
loadImageFromFilePath(filePath)
} catch (e: Exception) {
Toast.makeText(this, "加载失败: ${e.message}", Toast.LENGTH_SHORT).show()
}
}
private fun loadImageFromFilePath(filePath: String) {
val bitmap = BitmapFactory.decodeFile(filePath)
if (bitmap == null) {
Toast.makeText(this, "图片解码失败: $filePath", Toast.LENGTH_SHORT).show()
return
}
renderer.setImageBitmap(bitmap)
glSurfaceView.requestRender()
tvInfo.text = "✅ 已加载: $filePath\n尺寸: ${bitmap.width} × ${bitmap.height}"
Toast.makeText(this, "图片加载成功 (${bitmap.width}×${bitmap.height})", Toast.LENGTH_SHORT).show()
}
private fun exportTexture() {
if (loadedFilePath == null) {
Log.i(TAG, "exportTexture: 尚未加载图片, 中止导出")
Toast.makeText(this, "请先加载一张图片", Toast.LENGTH_SHORT).show()
return
}
Trace.beginSection("MainActivity#exportTexture")
val exportDir = File(getExternalFilesDir(null), "exports")
val exportFile = File(exportDir, "exported_${System.currentTimeMillis()}.jpg")
val exportPath = exportFile.absolutePath
Log.i(TAG, "exportTexture: 请求导出, 源文件=$loadedFilePath, 导出路径=$exportPath")
val requestTime = System.currentTimeMillis()
renderer.requestExport(exportPath) { success, message ->
val callbackTime = System.currentTimeMillis() - requestTime
runOnUiThread {
if (success) {
Log.i(TAG, "exportTexture: 导出成功回调, 从请求到回调耗时=${callbackTime}ms, 路径=$message")
tvInfo.text = "✅ 导出成功!\n路径: $message"
Toast.makeText(this, "导出成功, 正在插入相册...", Toast.LENGTH_SHORT).show()
insertToGalleryAndOpen(message)
} else {
Log.i(TAG, "exportTexture: 导出失败回调, 从请求到回调耗时=${callbackTime}ms, 原因=$message")
tvInfo.text = "❌ 导出失败: $message"
Toast.makeText(this, "导出失败: $message", Toast.LENGTH_SHORT).show()
}
}
}
glSurfaceView.requestRender()
Trace.endSection()
}
private fun insertToGalleryAndOpen(filePath: String) {
Trace.beginSection("MainActivity#insertToGalleryAndOpen")
val totalStart = System.currentTimeMillis()
Log.i(TAG, "insertToGalleryAndOpen: 开始, 源文件=$filePath")
try {
val file = File(filePath)
if (!file.exists()) {
Log.i(TAG, "insertToGalleryAndOpen: 文件不存在, 中止")
return
}
Trace.beginSection("insertToGallery#insertUri")
var stepStart = System.currentTimeMillis()
val fileName = file.name
val values = ContentValues().apply {
put(MediaStore.Images.Media.DISPLAY_NAME, fileName)
put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg")
put(MediaStore.Images.Media.DATE_ADDED, System.currentTimeMillis() / 1000)
put(MediaStore.Images.Media.DATE_MODIFIED, System.currentTimeMillis() / 1000)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
put(MediaStore.Images.Media.RELATIVE_PATH, Environment.DIRECTORY_PICTURES + "/PhotoTurboDemo")
put(MediaStore.Images.Media.IS_PENDING, 1)
}
}
val collection = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
val imageUri = contentResolver.insert(collection, values)
Trace.endSection()
Log.i(TAG, "insertToGalleryAndOpen: MediaStore插入URI耗时=${System.currentTimeMillis() - stepStart}ms, uri=$imageUri")
if (imageUri == null) {
Log.i(TAG, "insertToGalleryAndOpen: MediaStore插入失败, uri为null")
Toast.makeText(this, "插入相册失败", Toast.LENGTH_SHORT).show()
return
}
Trace.beginSection("insertToGallery#copyFile")
stepStart = System.currentTimeMillis()
contentResolver.openOutputStream(imageUri)?.use { outputStream ->
FileInputStream(file).use { inputStream ->
inputStream.copyTo(outputStream)
}
}
Trace.endSection()
Log.i(TAG, "insertToGalleryAndOpen: 文件拷贝到MediaStore耗时=${System.currentTimeMillis() - stepStart}ms, 文件大小=${file.length() / 1024}KB")
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
Trace.beginSection("insertToGallery#clearPending")
stepStart = System.currentTimeMillis()
val updateValues = ContentValues().apply {
put(MediaStore.Images.Media.IS_PENDING, 0)
}
contentResolver.update(imageUri, updateValues, null, null)
Trace.endSection()
Log.i(TAG, "insertToGalleryAndOpen: 清除IS_PENDING耗时=${System.currentTimeMillis() - stepStart}ms")
}
val totalTime = System.currentTimeMillis() - totalStart
Log.i(TAG, "insertToGalleryAndOpen: ===== 插入相册完成, 总耗时=${totalTime}ms, uri=$imageUri =====")
tvInfo.text = "✅ 已保存到相册!\nuri: $imageUri"
Toast.makeText(this, "已保存到相册", Toast.LENGTH_SHORT).show()
openImageInGallery(imageUri)
} catch (e: Exception) {
Log.i(TAG, "insertToGalleryAndOpen: 异常: ${e.message}", e)
Toast.makeText(this, "插入相册失败: ${e.message}", Toast.LENGTH_SHORT).show()
} finally {
Trace.endSection()
}
}
private fun openImageInGallery(uri: Uri) {
Trace.beginSection("MainActivity#openImageInGallery")
Log.i(TAG, "openImageInGallery: 打开图片查看器, uri=$uri")
try {
val intent = Intent(Intent.ACTION_VIEW).apply {
setDataAndType(uri, "image
纹理渲染器代码
package com.example.phototurbodemo
import android.graphics.Bitmap
import android.opengl.GLES30
import android.opengl.GLSurfaceView
import android.opengl.GLUtils
import android.os.Trace
import android.util.Log
import java.io.File
import java.io.FileOutputStream
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.nio.FloatBuffer
import javax.microedition.khronos.egl.EGLConfig
import javax.microedition.khronos.opengles.GL10
class TextureRenderer : GLSurfaceView.Renderer {
private val vertexData = floatArrayOf(
-1f, -1f,
1f, -1f,
-1f, 1f,
1f, 1f
)
private val texCoordData = floatArrayOf(
0f, 1f,
1f, 1f,
0f, 0f,
1f, 0f
)
private lateinit var vertexBuffer: FloatBuffer
private lateinit var texCoordBuffer: FloatBuffer
private var program = 0
private var textureId = 0
private var hasTexture = false
private var viewWidth = 0
private var viewHeight = 0
private var imageWidth = 0
private var imageHeight = 0
private val mvpMatrix = FloatArray(16)
@Volatile
private var pendingBitmap: Bitmap? = null
@Volatile
private var exportFilePath: String? = null
private var exportCallback: ((Boolean, String) -> Unit)? = null
companion object {
private const val TAG = "yang"
private const val VERTEX_SHADER = """#version 300 es
in vec4 aPosition;
in vec2 aTexCoord;
out vec2 vTexCoord;
uniform mat4 uMVPMatrix;
void main() {
gl_Position = uMVPMatrix * aPosition;
vTexCoord = aTexCoord;
}
"""
private const val FRAGMENT_SHADER = """#version 300 es
precision mediump float;
in vec2 vTexCoord;
uniform sampler2D uTexture;
out vec4 fragColor;
void main() {
fragColor = texture(uTexture, vTexCoord);
}
"""
}
fun setImageBitmap(bitmap: Bitmap) {
pendingBitmap = bitmap
}
fun requestExport(filePath: String, callback: (Boolean, String) -> Unit) {
exportCallback = callback
exportFilePath = filePath
}
override fun onSurfaceCreated(gl: GL10?, config: EGLConfig?) {
GLES30.glClearColor(0.15f, 0.15f, 0.15f, 1.0f)
vertexBuffer = ByteBuffer.allocateDirect(vertexData.size * 4)
.order(ByteOrder.nativeOrder())
.asFloatBuffer()
.put(vertexData)
vertexBuffer.position(0)
texCoordBuffer = ByteBuffer.allocateDirect(texCoordData.size * 4)
.order(ByteOrder.nativeOrder())
.asFloatBuffer()
.put(texCoordData)
texCoordBuffer.position(0)
program = createProgram(VERTEX_SHADER, FRAGMENT_SHADER)
android.opengl.Matrix.setIdentityM(mvpMatrix, 0)
}
override fun onSurfaceChanged(gl: GL10?, width: Int, height: Int) {
viewWidth = width
viewHeight = height
GLES30.glViewport(0, 0, width, height)
updateFitCenterMatrix()
}
override fun onDrawFrame(gl: GL10?) {
pendingBitmap?.let { bitmap ->
loadTexture(bitmap)
pendingBitmap = null
}
GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT)
if (!hasTexture) return
drawTexture(mvpMatrix)
exportFilePath?.let { path ->
performExport(path)
exportFilePath = null
}
}
private fun drawTexture(matrix: FloatArray) {
GLES30.glUseProgram(program)
val posHandle = GLES30.glGetAttribLocation(program, "aPosition")
GLES30.glEnableVertexAttribArray(posHandle)
vertexBuffer.position(0)
GLES30.glVertexAttribPointer(posHandle, 2, GLES30.GL_FLOAT, false, 0, vertexBuffer)
val texHandle = GLES30.glGetAttribLocation(program, "aTexCoord")
GLES30.glEnableVertexAttribArray(texHandle)
texCoordBuffer.position(0)
GLES30.glVertexAttribPointer(texHandle, 2, GLES30.GL_FLOAT, false, 0, texCoordBuffer)
val mvpHandle = GLES30.glGetUniformLocation(program, "uMVPMatrix")
GLES30.glUniformMatrix4fv(mvpHandle, 1, false, matrix, 0)
GLES30.glActiveTexture(GLES30.GL_TEXTURE0)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, textureId)
val samplerHandle = GLES30.glGetUniformLocation(program, "uTexture")
GLES30.glUniform1i(samplerHandle, 0)
GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, 4)
GLES30.glDisableVertexAttribArray(posHandle)
GLES30.glDisableVertexAttribArray(texHandle)
}
private fun loadTexture(bitmap: Bitmap) {
imageWidth = bitmap.width
imageHeight = bitmap.height
if (textureId != 0) {
GLES30.glDeleteTextures(1, intArrayOf(textureId), 0)
}
val texIds = IntArray(1)
GLES30.glGenTextures(1, texIds, 0)
textureId = texIds[0]
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, textureId)
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MIN_FILTER, GLES30.GL_LINEAR)
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MAG_FILTER, GLES30.GL_LINEAR)
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_WRAP_S, GLES30.GL_CLAMP_TO_EDGE)
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_WRAP_T, GLES30.GL_CLAMP_TO_EDGE)
GLUtils.texImage2D(GLES30.GL_TEXTURE_2D, 0, bitmap, 0)
hasTexture = true
updateFitCenterMatrix()
}
private fun updateFitCenterMatrix() {
android.opengl.Matrix.setIdentityM(mvpMatrix, 0)
if (imageWidth == 0 || imageHeight == 0 || viewWidth == 0 || viewHeight == 0) return
val imageAspect = imageWidth.toFloat() / imageHeight.toFloat()
val viewAspect = viewWidth.toFloat() / viewHeight.toFloat()
val scaleX: Float
val scaleY: Float
if (imageAspect > viewAspect) {
scaleX = 1f
scaleY = viewAspect / imageAspect
} else {
scaleX = imageAspect / viewAspect
scaleY = 1f
}
android.opengl.Matrix.scaleM(mvpMatrix, 0, scaleX, scaleY, 1f)
}
private fun performExport(filePath: String) {
Trace.beginSection("TextureRenderer#performExport")
val exportStartTime = System.currentTimeMillis()
Log.i(TAG, "performExport: 开始导出, 图片尺寸=${imageWidth}x${imageHeight}, 目标路径=$filePath")
if (!hasTexture || imageWidth == 0 || imageHeight == 0) {
Log.i(TAG, "performExport: 没有已加载的纹理, 中止导出")
exportCallback?.invoke(false, "没有已加载的纹理")
exportCallback = null
Trace.endSection()
return
}
val fbo = IntArray(1)
val renderTex = IntArray(1)
try {
Trace.beginSection("performExport#createFBO")
var stepStart = System.currentTimeMillis()
GLES30.glGenTextures(1, renderTex, 0)
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, renderTex[0])
GLES30.glGenFramebuffers(1, fbo, 0)
GLES30.glTexImage2D(
GLES30.GL_TEXTURE_2D, 0, GLES30.GL_RGBA,
imageWidth, imageHeight, 0,
GLES30.GL_RGBA, GLES30.GL_UNSIGNED_BYTE, null
)
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MIN_FILTER, GLES30.GL_LINEAR)
GLES30.glTexParameteri(GLES30.GL_TEXTURE_2D, GLES30.GL_TEXTURE_MAG_FILTER, GLES30.GL_LINEAR)
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, fbo[0])
GLES30.glFramebufferTexture2D(
GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0,
GLES30.GL_TEXTURE_2D, renderTex[0], 0
)
val status = GLES30.glCheckFramebufferStatus(GLES30.GL_FRAMEBUFFER)
Trace.endSection()
Log.i(TAG, "performExport: 创建FBO耗时=${System.currentTimeMillis() - stepStart}ms, status=$status")
if (status != GLES30.GL_FRAMEBUFFER_COMPLETE) {
Log.i(TAG, "performExport: FBO创建失败, status=$status")
exportCallback?.invoke(false, "FBO创建失败: $status")
exportCallback = null
return
}
Trace.beginSection("performExport#drawToFBO")
stepStart = System.currentTimeMillis()
GLES30.glViewport(0, 0, imageWidth, imageHeight)
GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT)
val flipYMatrix = FloatArray(16)
android.opengl.Matrix.setIdentityM(flipYMatrix, 0)
android.opengl.Matrix.scaleM(flipYMatrix, 0, 1f, -1f, 1f)
drawTexture(flipYMatrix)
Trace.endSection()
Log.i(TAG, "performExport: FBO离屏渲染(含GPU翻转)耗时=${System.currentTimeMillis() - stepStart}ms")
Trace.beginSection("performExport#glReadPixels")
stepStart = System.currentTimeMillis()
val buffer = ByteBuffer.allocateDirect(imageWidth * imageHeight * 4)
buffer.order(ByteOrder.nativeOrder())
GLES30.glReadPixels(
0, 0, imageWidth, imageHeight,
GLES30.GL_RGBA, GLES30.GL_UNSIGNED_BYTE, buffer
)
buffer.rewind()
Trace.endSection()
Log.i(TAG, "performExport: glReadPixels耗时=${System.currentTimeMillis() - stepStart}ms, bufferSize=${buffer.capacity()}bytes")
Trace.beginSection("performExport#copyPixels")
stepStart = System.currentTimeMillis()
val bitmap = Bitmap.createBitmap(imageWidth, imageHeight, Bitmap.Config.ARGB_8888)
bitmap.copyPixelsFromBuffer(buffer)
Trace.endSection()
Log.i(TAG, "performExport: copyPixelsFromBuffer耗时=${System.currentTimeMillis() - stepStart}ms")
Trace.beginSection("performExport#writeFile")
stepStart = System.currentTimeMillis()
val file = File(filePath)
file.parentFile?.mkdirs()
FileOutputStream(file).use { fos ->
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos)
}
bitmap.recycle()
Trace.endSection()
val fileSize = File(filePath).length()
Log.i(TAG, "performExport: Bitmap写入文件(JPEG,100)耗时=${System.currentTimeMillis() - stepStart}ms, 文件大小=${fileSize / 1024}KB")
val totalTime = System.currentTimeMillis() - exportStartTime
Log.i(TAG, "performExport: ===== 导出完成, 总耗时=${totalTime}ms, 路径=$filePath =====")
exportCallback?.invoke(true, filePath)
} catch (e: Exception) {
Log.i(TAG, "performExport: 导出异常: ${e.message}", e)
exportCallback?.invoke(false, "导出异常: ${e.message}")
} finally {
Trace.beginSection("performExport#cleanup")
GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0)
GLES30.glDeleteFramebuffers(1, fbo, 0)
GLES30.glDeleteTextures(1, renderTex, 0)
GLES30.glViewport(0, 0, viewWidth, viewHeight)
Trace.endSection()
exportCallback = null
Trace.endSection()
}
}
private fun createProgram(vertexSource: String, fragmentSource: String): Int {
val vertexShader = loadShader(GLES30.GL_VERTEX_SHADER, vertexSource)
val fragmentShader = loadShader(GLES30.GL_FRAGMENT_SHADER, fragmentSource)
val program = GLES30.glCreateProgram()
GLES30.glAttachShader(program, vertexShader)
GLES30.glAttachShader(program, fragmentShader)
GLES30.glLinkProgram(program)
val linkStatus = IntArray(1)
GLES30.glGetProgramiv(program, GLES30.GL_LINK_STATUS, linkStatus, 0)
if (linkStatus[0] == 0) {
val log = GLES30.glGetProgramInfoLog(program)
GLES30.glDeleteProgram(program)
throw RuntimeException("Program link failed: $log")
}
return program
}
private fun loadShader(type: Int, source: String): Int {
val shader = GLES30.glCreateShader(type)
GLES30.glShaderSource(shader, source)
GLES30.glCompileShader(shader)
val compileStatus = IntArray(1)
GLES30.glGetShaderiv(shader, GLES30.GL_COMPILE_STATUS, compileStatus, 0)
if (compileStatus[0] == 0) {
val log = GLES30.glGetShaderInfoLog(shader)
GLES30.glDeleteShader(shader)
throw RuntimeException("Shader compile failed: $log")
}
return shader
}
}