将图像从 ImageView 保存到内部存储
Saving an image from ImageView into internal storage
我创建了一个 ImageView,我可以看到相机的预览,并将捕获的图像加载到 ImageView 中,我想将图像存储到内存中的一个目录中。我参考了很多帖子并尝试过,但我在内存中找不到我的图片。
这是我用过的代码:
package com.example.shravan.camera;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
private final String TAG = "abc";
static final int REQUEST_IMAGE_CAPTURE =1 ;
ImageView iv;
Uri imageUri;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button)findViewById(R.id.myB);
iv = (ImageView) findViewById(R.id.myIV);
//disable the button if the user has no camera
if (!hasCamera()) {
btn.setEnabled(false);
}
}
public boolean hasCamera() {
return getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY);
}
//on click event handler that launches the camera
public void launchCamera(View v) {
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i, REQUEST_IMAGE_CAPTURE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
imageUri=data.getData();
iv.setImageURI(imageUri);;
}
}
public void SaveFile(View v) {
BitmapDrawable drawable = (BitmapDrawable) iv.getDrawable();
Bitmap bitmap = drawable.getBitmap();
print("Creating cw");
ContextWrapper cw = new ContextWrapper(this.getApplicationContext());
print("Creating dir");
File directory = cw.getDir("ImagesDir", Context.MODE_PRIVATE);
print("Created dir" + directory);
File mypath = new File(directory,"myImagesDGS.jpg");
print("path is" + mypath);
FileOutputStream fos = null;
try {
print("creating fos");
fos = new FileOutputStream(mypath);
print("Compressing bitmap");
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fos.close();
print("fos closed");
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void print(String str){
Log.d(TAG, str);
}
}
我制作了许多要调试的日志消息,但我得到了一条在 phone 中找不到的路径。
这是logcat:
08-07 21:47:37.089 11030-11030/com.example.shravan.camera D/abc:
Creating cw 08-07
21:47:37.089 11030-11030/com.example.shravan.camera
D/abc: Creating dir 08-07
21:47:37.099
11030-11030/com.example.shravan.camera D/abc: Created
dir/data/user/0/com.example.shravan.camera/app_ImagesDir 08-07
21:47:37.099 11030-11030/com.example.shravan.camera D/abc: path
is/data/user/0/com.example.shravan.camera/app_ImagesDir/myImagesDGS.jpg
08-07 21:47:37.099 11030-11030/com.example.shravan.camera D/abc:
creating fos
08-07 21:47:37.099 11030-11030/com.example.shravan.camera
D/abc: Compressing bitmap
08-07 21:47:42.589
11030-11030/com.example.shravan.camera D/abc: fos closed
有什么我需要检查并且应该更改的吗?请帮忙!
您的图像正在从该路径保存/data/user/0/com.example.shravan.camera/app_ImagesDir/myImagesDGS.jpg
但你不是 access.try iamge 的代码 reading.Call 这个方法到 onCreate 这个方法是 return 你位图。
Bitmap mBitmap= getImageBitmap(this,"myImagesDGS","jpg");
if(mBitmap !=null){
yourImageView.setBitmap(mBitmap);
}else{
Log.d("MainActivity","Image is not found");
}
是sepread方法
public Bitmap getImageBitmap(Context context,String name,String extension){
name=name+"."+extension;
try{
FileInputStream fis = context.openFileInput(name);
Bitmap b = BitmapFactory.decodeStream(fis);
fis.close();
return b;
}
catch(Exception e){
}
return null;
}
试试这个。我修改了我的代码以适合您提供的代码。我没有测试它。我将拍摄的照片临时存储到一个带有时间戳的文件中,然后使用文件名来检索文件。希望对你有帮助
private Uri mImageCaptureUri;
public void launchCamera(View v)
{
//Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//startActivityForResult(i, REQUEST_IMAGE_CAPTURE);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
mImageCaptureUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
"tmp_avatar_" + String.valueOf(System.currentTimeMillis()) + ".jpg"));
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (mImageCaptureUri!=null){
//Do whatever you want with the uri
}
}
}
使用该代码,您将结束将文件存储到您的私人应用程序数据。 除了您的应用程序本身,如果没有 root 访问权限,您将无法使用其他应用程序访问该数据。如果您希望图像文件可以被其他应用程序访问,您可以在声明文件路径时使用此代码获取 public 图像目录。
File albumF;
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
albumF = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
} else {
albumF = context.getFilesDir();
}
如果你需要在public画廊目录中创建你的子目录,你可以像这样更改上面的代码:
File albumF;
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
albumF = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DCIM), YOUR_SUB_DIRECTORY_STRING);
} else {
albumF = new File(context.getFilesDir(), YOUR_SUB_DIRECTORY_STRING);
}
您可能需要添加此代码才能创建该专辑目录
if (!albumF.exists()) {
albumF.mkdirs();
}
您当前图像的保存位置,其他人无法访问 application.It 最好将它们保存在可访问的 location.try 中,例如这样..
BitmapDrawable drawable = (BitmapDrawable) iv.getDrawable();
Bitmap bitmap = drawable.getBitmap();
try {
String root = Environment.getExternalStorageDirectory().toString();
File file = new File(root + "/YourDirectory/myImagesDGS.jpg");
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
} catch (Exception ex) {
ex.printStackTrace();
}
然后您可以像这样检索您保存的图像..
String root = Environment.getExternalStorageDirectory().toString();
File file = new File(root + "/YourDirectory/myImagesDGS.jpg");
Bitmap bmap=BitmapFactory.decodeFile(file.getAbsolutePath());
尝试使用 ImageSaver。这是一种从内部和外部存储中保存和加载图像的同步方式。
用法
保存:
new ImageSaver(context).
setFileName("myImage.png").
setDirectoryName("images").
setExternal(true).
save(bitmap);
要加载:
Bitmap bitmap = new ImageSaver(context).
setFileName("myImage.png").
setDirectoryName("images").
setExternal(true).
load();
成功了!
我使用这段代码在我的文件存储中创建了一个目录,然后存储图像:
FileOutputStream outStream = null;
// Write to SD Card
try {
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File(sdCard.getAbsolutePath() + "/camtest");
dir.mkdirs();
String fileName = String.format("%d.jpg", System.currentTimeMillis());
File outFile = new File(dir, fileName);
outStream = new FileOutputStream(outFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
outStream.flush();
outStream.close();
Log.d(TAG, "onPictureTaken - wrote to " + outFile.getAbsolutePath());
refreshGallery(outFile);
} catch (FileNotFoundException e) {
print("FNF");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
我的权限:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
最后,最重要的是:
转到设备设置>设备>应用程序>应用程序管理器>"your app">权限>启用存储权限!
@Shravan DG 提出的解决方案对我来说是错误的。我稍微修改了他的代码,没有错误。
private void downloadQR()
{
FileOutputStream outStream = null;
try {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "QRCode_" + timeStamp + ".jpg";
File storageDir = new File(Environment.getExternalStorageDirectory().toString(), "PARENT_DIR)/CHILD_DIR/");
storageDir.mkdirs();
File outFile = new File(storageDir, imageFileName);
outStream = new FileOutputStream(outFile);
BitmapDrawable drawable = (BitmapDrawable) qrCode.getDrawable();
Bitmap bitmap = drawable.getBitmap();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
outStream.flush();
outStream.close();
Log.d(TAG, "onPictureTaken - wrote to " + outFile.getAbsolutePath());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
}
镇痛丸:)
我创建了一个 ImageView,我可以看到相机的预览,并将捕获的图像加载到 ImageView 中,我想将图像存储到内存中的一个目录中。我参考了很多帖子并尝试过,但我在内存中找不到我的图片。
这是我用过的代码:
package com.example.shravan.camera;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
private final String TAG = "abc";
static final int REQUEST_IMAGE_CAPTURE =1 ;
ImageView iv;
Uri imageUri;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button)findViewById(R.id.myB);
iv = (ImageView) findViewById(R.id.myIV);
//disable the button if the user has no camera
if (!hasCamera()) {
btn.setEnabled(false);
}
}
public boolean hasCamera() {
return getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY);
}
//on click event handler that launches the camera
public void launchCamera(View v) {
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i, REQUEST_IMAGE_CAPTURE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
imageUri=data.getData();
iv.setImageURI(imageUri);;
}
}
public void SaveFile(View v) {
BitmapDrawable drawable = (BitmapDrawable) iv.getDrawable();
Bitmap bitmap = drawable.getBitmap();
print("Creating cw");
ContextWrapper cw = new ContextWrapper(this.getApplicationContext());
print("Creating dir");
File directory = cw.getDir("ImagesDir", Context.MODE_PRIVATE);
print("Created dir" + directory);
File mypath = new File(directory,"myImagesDGS.jpg");
print("path is" + mypath);
FileOutputStream fos = null;
try {
print("creating fos");
fos = new FileOutputStream(mypath);
print("Compressing bitmap");
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fos.close();
print("fos closed");
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void print(String str){
Log.d(TAG, str);
}
}
我制作了许多要调试的日志消息,但我得到了一条在 phone 中找不到的路径。
这是logcat:
08-07 21:47:37.089 11030-11030/com.example.shravan.camera D/abc: Creating cw 08-07
21:47:37.089 11030-11030/com.example.shravan.camera D/abc: Creating dir 08-07
21:47:37.099 11030-11030/com.example.shravan.camera D/abc: Created dir/data/user/0/com.example.shravan.camera/app_ImagesDir 08-07
21:47:37.099 11030-11030/com.example.shravan.camera D/abc: path is/data/user/0/com.example.shravan.camera/app_ImagesDir/myImagesDGS.jpg
08-07 21:47:37.099 11030-11030/com.example.shravan.camera D/abc: creating fos
08-07 21:47:37.099 11030-11030/com.example.shravan.camera D/abc: Compressing bitmap
08-07 21:47:42.589 11030-11030/com.example.shravan.camera D/abc: fos closed
有什么我需要检查并且应该更改的吗?请帮忙!
您的图像正在从该路径保存/data/user/0/com.example.shravan.camera/app_ImagesDir/myImagesDGS.jpg
但你不是 access.try iamge 的代码 reading.Call 这个方法到 onCreate 这个方法是 return 你位图。
Bitmap mBitmap= getImageBitmap(this,"myImagesDGS","jpg");
if(mBitmap !=null){
yourImageView.setBitmap(mBitmap);
}else{
Log.d("MainActivity","Image is not found");
}
是sepread方法
public Bitmap getImageBitmap(Context context,String name,String extension){
name=name+"."+extension;
try{
FileInputStream fis = context.openFileInput(name);
Bitmap b = BitmapFactory.decodeStream(fis);
fis.close();
return b;
}
catch(Exception e){
}
return null;
}
试试这个。我修改了我的代码以适合您提供的代码。我没有测试它。我将拍摄的照片临时存储到一个带有时间戳的文件中,然后使用文件名来检索文件。希望对你有帮助
private Uri mImageCaptureUri;
public void launchCamera(View v)
{
//Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//startActivityForResult(i, REQUEST_IMAGE_CAPTURE);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
mImageCaptureUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
"tmp_avatar_" + String.valueOf(System.currentTimeMillis()) + ".jpg"));
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (mImageCaptureUri!=null){
//Do whatever you want with the uri
}
}
}
使用该代码,您将结束将文件存储到您的私人应用程序数据。 除了您的应用程序本身,如果没有 root 访问权限,您将无法使用其他应用程序访问该数据。如果您希望图像文件可以被其他应用程序访问,您可以在声明文件路径时使用此代码获取 public 图像目录。
File albumF;
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
albumF = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
} else {
albumF = context.getFilesDir();
}
如果你需要在public画廊目录中创建你的子目录,你可以像这样更改上面的代码:
File albumF;
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
albumF = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DCIM), YOUR_SUB_DIRECTORY_STRING);
} else {
albumF = new File(context.getFilesDir(), YOUR_SUB_DIRECTORY_STRING);
}
您可能需要添加此代码才能创建该专辑目录
if (!albumF.exists()) {
albumF.mkdirs();
}
您当前图像的保存位置,其他人无法访问 application.It 最好将它们保存在可访问的 location.try 中,例如这样..
BitmapDrawable drawable = (BitmapDrawable) iv.getDrawable();
Bitmap bitmap = drawable.getBitmap();
try {
String root = Environment.getExternalStorageDirectory().toString();
File file = new File(root + "/YourDirectory/myImagesDGS.jpg");
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
} catch (Exception ex) {
ex.printStackTrace();
}
然后您可以像这样检索您保存的图像..
String root = Environment.getExternalStorageDirectory().toString();
File file = new File(root + "/YourDirectory/myImagesDGS.jpg");
Bitmap bmap=BitmapFactory.decodeFile(file.getAbsolutePath());
尝试使用 ImageSaver。这是一种从内部和外部存储中保存和加载图像的同步方式。
用法
保存:
new ImageSaver(context). setFileName("myImage.png"). setDirectoryName("images"). setExternal(true). save(bitmap);
要加载:
Bitmap bitmap = new ImageSaver(context). setFileName("myImage.png"). setDirectoryName("images"). setExternal(true). load();
成功了!
我使用这段代码在我的文件存储中创建了一个目录,然后存储图像:
FileOutputStream outStream = null;
// Write to SD Card
try {
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File(sdCard.getAbsolutePath() + "/camtest");
dir.mkdirs();
String fileName = String.format("%d.jpg", System.currentTimeMillis());
File outFile = new File(dir, fileName);
outStream = new FileOutputStream(outFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
outStream.flush();
outStream.close();
Log.d(TAG, "onPictureTaken - wrote to " + outFile.getAbsolutePath());
refreshGallery(outFile);
} catch (FileNotFoundException e) {
print("FNF");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
我的权限:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
最后,最重要的是:
转到设备设置>设备>应用程序>应用程序管理器>"your app">权限>启用存储权限!
@Shravan DG 提出的解决方案对我来说是错误的。我稍微修改了他的代码,没有错误。
private void downloadQR()
{
FileOutputStream outStream = null;
try {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "QRCode_" + timeStamp + ".jpg";
File storageDir = new File(Environment.getExternalStorageDirectory().toString(), "PARENT_DIR)/CHILD_DIR/");
storageDir.mkdirs();
File outFile = new File(storageDir, imageFileName);
outStream = new FileOutputStream(outFile);
BitmapDrawable drawable = (BitmapDrawable) qrCode.getDrawable();
Bitmap bitmap = drawable.getBitmap();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
outStream.flush();
outStream.close();
Log.d(TAG, "onPictureTaken - wrote to " + outFile.getAbsolutePath());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
}
镇痛丸:)