以下是一个使用Android存储(MediaStore)的代码示例:
import android.content.ContentResolver;
import android.content.ContentValues;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaScannerConnection;
import android.os.Environment;
import android.provider.MediaStore;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
public class MainActivity extends AppCompatActivity {
private static final String IMAGE_DIRECTORY = "/your_image_directory";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 假设你有一个名为"your_bitmap.jpg"的位图
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.your_bitmap);
// 保存图片到MediaStore
String savedImagePath = saveImageToMediaStore(bitmap);
if (savedImagePath != null) {
Toast.makeText(this, "图片已保存到:" + savedImagePath, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "保存图片失败", Toast.LENGTH_SHORT).show();
}
}
private String saveImageToMediaStore(Bitmap bitmap) {
String savedImagePath = null;
// 创建要保存图片的目录
File imageDirectory = new File(Environment.getExternalStorageDirectory() + IMAGE_DIRECTORY);
if (!imageDirectory.exists()) {
imageDirectory.mkdirs();
}
// 创建图片文件
String fileName = "your_image_file_name.jpg";
File imageFile = new File(imageDirectory, fileName);
savedImagePath = imageFile.getAbsolutePath();
try {
// 将位图保存到文件
OutputStream fOut = new FileOutputStream(imageFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
fOut.flush();
fOut.close();
// 将图片添加到MediaStore数据库
ContentResolver contentResolver = getContentResolver();
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis());
contentValues.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
contentValues.put(MediaStore.MediaColumns.DATA, savedImagePath);
contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
// 通知媒体库更新
MediaScannerConnection.scanFile(this, new String[]{imageFile.getAbsolutePath()}, null, null);
} catch (Exception e) {
e.printStackTrace();
savedImagePath = null;
}
return savedImagePath;
}
}
注意:上述代码中的"your_image_directory"和"your_image_file_name.jpg"需要根据你的需求进行替换。此外,保存图片到MediaStore需要的存储权限需要在运行时进行请求和授予。