You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Studio调用相机拍照调整大小后通过JDBC上传PNG到MSSQL

Android拍照后调整大小、本地存储及JDBC上传MSSQL实现方案

一、前置配置

1. 清单文件权限配置(AndroidManifest.xml)

<!-- 网络权限 用于JDBC连接数据库 -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- 存储权限 用于保存图片到本地 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

2. 依赖导入(build.gradle(Module级))

dependencies {
    // MSSQL JDBC驱动
    implementation 'com.microsoft.sqlserver:mssql-jdbc:12.4.2.jre8'
}

二、图片尺寸调整工具方法

可根据需求自定义目标宽高,自动保持原图比例避免拉伸

public static Bitmap resizeBitmap(Bitmap originalBitmap, int maxWidth, int maxHeight) {
    int width = originalBitmap.getWidth();
    int height = originalBitmap.getHeight();
    float scaleRatio = Math.min((float) maxWidth / width, (float) maxHeight / height);
    Matrix matrix = new Matrix();
    matrix.postScale(scaleRatio, scaleRatio);
    return Bitmap.createBitmap(originalBitmap, 0, 0, width, height, matrix, false);
}

三、图片保存到内部存储实现

private String savePngToInternalStorage(Bitmap bitmap, String fileName) {
    Context context = getApplicationContext();
    try {
        // 打开内部存储输出流,仅当前应用可访问
        FileOutputStream fos = context.openFileOutput(fileName + ".png", Context.MODE_PRIVATE);
        // 压缩为PNG格式,质量100为无损
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
        fos.close();
        // 返回存储路径供后续使用
        return context.getFilesDir() + "/" + fileName + ".png";
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

四、JDBC上传PNG图片到MSSQL实现

注意:JDBC属于网络IO操作,必须在子线程中执行,禁止在主线程直接调用

1. 数据表参考结构(MSSQL端)

CREATE TABLE [dbo].[UploadImages](
	[id] [int] IDENTITY(1,1) PRIMARY KEY NOT NULL,
	[file_name] [varchar](255) NULL,
	[image_data] [varbinary](max) NULL,
	[upload_time] [datetime] DEFAULT getdate() NULL
)

2. 上传逻辑代码

// 先将Bitmap转为字节数组
private byte[] bitmapToByteArray(Bitmap bitmap) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
    return baos.toByteArray();
}

// 子线程执行上传逻辑
private void uploadImageToMssql(String fileName, byte[] imageData) {
    new Thread(() -> {
        Connection conn = null;
        PreparedStatement pstmt = null;
        // 数据库连接配置,替换为自己的实际参数
        String dbUrl = "jdbc:sqlserver://你的数据库IP:端口;databaseName=库名;encrypt=false;";
        String dbUser = "账号";
        String dbPwd = "密码";
        
        try {
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            conn = DriverManager.getConnection(dbUrl, dbUser, dbPwd);
            String sql = "INSERT INTO UploadImages (file_name, image_data) VALUES (?, ?)";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, fileName);
            pstmt.setBytes(2, imageData);
            int result = pstmt.executeUpdate();
            if(result > 0) {
                // 上传成功可切回主线程更新UI
                runOnUiThread(() -> Toast.makeText(InstallForm.this, "图片上传成功", Toast.LENGTH_SHORT).show());
            }
        } catch (Exception e) {
            e.printStackTrace();
            runOnUiThread(() -> Toast.makeText(InstallForm.this, "上传失败:" + e.getMessage(), Toast.LENGTH_SHORT).show());
        } finally {
            try {
                if(pstmt != null) pstmt.close();
                if(conn != null) conn.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }).start();
}

五、原有拍照逻辑对接修改

在你原有onActivityResult中拿到resultPhoto之后添加如下逻辑即可:

if (requestCode == CameraRequest) {
    clear.setVisibility(View.VISIBLE);
    imgView.setVisibility(View.VISIBLE);
    uploadimage.setVisibility(View.VISIBLE);
    resultPhoto = (Bitmap) Objects.requireNonNull(data.getExtras()).get("data");
    imgView.setImageBitmap(resultPhoto);
    filename.setText(" service Image " + number);
    
    // 新增逻辑
    // 1. 调整图片尺寸,示例最大宽高为1080*1920可自行修改
    Bitmap resizedBitmap = resizeBitmap(resultPhoto, 1080, 1920);
    // 2. 保存到本地内部存储
    String savePath = savePngToInternalStorage(resizedBitmap, "service_image_" + number);
    Log.d("存储路径", savePath);
    // 3. 上传到MSSQL
    byte[] imageBytes = bitmapToByteArray(resizedBitmap);
    uploadImageToMssql("service_image_" + number + ".png", imageBytes);
}

注意事项

  • 客户端直接通过JDBC连接数据库存在账号泄露风险,生产环境建议新增后端接口做数据中转,客户端通过HTTP接口上传
  • Android 6.0及以上版本需要动态申请存储权限后才能正常保存图片
  • 高版本JDBC驱动默认开启加密校验,如果数据库未配置SSL需在连接地址添加encrypt=false参数

内容的提问来源于stack exchange,提问作者Reza

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 05:54:03