bitmap 保存到 sd卡根目录,png格式
时间: 2023-08-18 20:04:14 浏览: 53
保存 Bitmap 到 SD 卡根目录,可以使用以下代码:
```java
// 首先要获取 SD 卡根目录的路径
String root = Environment.getExternalStorageDirectory().getAbsolutePath();
// 创建目录
File directory = new File(root);
if (!directory.exists()) {
directory.mkdirs();
}
// 创建文件
File file = new File(root, "image.png");
// 将 Bitmap 保存到文件
try {
FileOutputStream fos = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
```
在上面的代码中,首先获取 SD 卡根目录的路径,然后创建目录,接着创建要保存的文件,最后将 Bitmap 保存到文件中。其中,Bitmap 的压缩格式指定为 PNG 格式,压缩质量为 100,表示不压缩,直接保存原图。保存的文件名为 "image.png"。
相关问题
androidbitmap保存到本地
要将Android中的位图(Bitmap)保存到本地,请按照以下步骤操作:
1. 创建一个位图对象,例如:Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.image);
2. 创建一个文件对象并指定保存路径,例如:File file = new File(Environment.getExternalStorageDirectory(), "image.png");
3. 创建一个文件输出流对象,例如:FileOutputStream fos = new FileOutputStream(file);
4. 使用Bitmap的compress()方法将位图保存到文件输出流中,例如:bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
5. 最后,关闭文件输出流对象,例如:fos.close();
完整代码示例:
```java
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.image);
File file = new File(Environment.getExternalStorageDirectory(), "image.png");
FileOutputStream fos = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
```
请注意,在使用此代码之前,您需要在AndroidManifest.xml文件中添加以下权限:
```xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
```
如何把bitmap保存到本地
要将Bitmap保存到本地,您可以使用以下代码:
```java
OutputStream outputStream = null;
File file = new File(Environment.getExternalStorageDirectory() + "/image.jpg");
try {
outputStream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
outputStream.flush();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
```
这段代码将Bitmap保存为JPEG格式的图像到外部存储器的根目录下的名为“image.jpg”的文件中。您也可以使用其他格式,例如PNG。请注意,您在使用此代码时需要添加权限:`<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />`
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)