在安卓端保存图片到MySQL数据库需要经历三个核心步骤:
// 获取图片并转换为字节数组 public byte[] getImageBytes(Uri uri) throws IOException { InputStream inputStream = getContentResolver().openInputStream(uri); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len; while ((len = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, len); } return outputStream.toByteArray(); }
// 使用OkHttp发送二进制数据 OkHttpClient client = new OkHttpClient(); RequestBody body = RequestBody.create(MediaType.parse("application/octet-stream"), imageBytes); Request request = new Request.Builder() .url("http://yourserver.com/api/upload") .post(body) .build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { // 处理失败 } @Override public void onResponse(Call call, Response response) throws IOException { // 处理成功响应 } });
// Spring Boot控制器示例 @PostMapping("/api/upload") public ResponseEntity<String> uploadImage(@RequestBody byte[] imageData) { try { // 数据库连接配置 Class.forName("com.mysql.cj.jdbc.Driver"); Connection conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/testdb", "username", "password"); // 插入BLOB数据 String sql = "INSERT INTO images (image_data) VALUES (?)"; PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.setBytes(1, imageData); pstmt.executeUpdate(); conn.close(); return ResponseEntity.ok("上传成功"); } catch (Exception e) { return ResponseEntity.status(500).body("服务器错误"); } }
字段名 | 数据类型 | 说明 |
---|---|---|
id | INT AUTO_INCREMENT | 主键ID |
image_data | LONGBLOB | 存储图片二进制数据 |
created_at | TIMESTAMP | 创建时间 |
性能优化:
安全措施:
异常处理:
A1:通过HTTP接口获取BLOB数据,转换为Bitmap后显示:
// 服务器端返回Base64编码的图片数据 String base64Image = result.getString("image_data"); byte[] imageBytes = Base64.decode(base64Image, Base64.DEFAULT); Bitmap bitmap = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length); imageView.setImageBitmap(bitmap);
A2:建议采取以下优化方案:
| 方案 | 说明 |
|———————|———————————————————————-|
| 图片压缩 | 使用Bitmap.compress()降低分辨率和质量 |
| 分块传输 | 将图片分割为多个小块分别上传 |
| 异步处理 | 使用RxJava或Coroutine进行后台处理 |
| 数据库优化 | 调整innodb_log_file_size参数,启用BLOB字段索引