답변:
아래 코드를 사용하여 이미지를 내부 디렉토리에 저장하십시오.
private String saveToInternalStorage(Bitmap bitmapImage){
ContextWrapper cw = new ContextWrapper(getApplicationContext());
// path to /data/data/yourapp/app_data/imageDir
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
// Create imageDir
File mypath=new File(directory,"profile.jpg");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mypath);
// Use the compress method on the BitMap object to write image to the OutputStream
bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return directory.getAbsolutePath();
}
설명 :
1. 주어진 이름으로 디렉토리가 생성됩니다. Javadocs는 디렉토리를 생성 할 위치를 정확히 알려줍니다.
2. 저장할 이미지 이름을 지정해야합니다.
내부 메모리에서 파일을 읽습니다. 아래 코드 사용
private void loadImageFromStorage(String path)
{
try {
File f=new File(path, "profile.jpg");
Bitmap b = BitmapFactory.decodeStream(new FileInputStream(f));
ImageView img=(ImageView)findViewById(R.id.imgPicker);
img.setImageBitmap(b);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
/**
* Created by Ilya Gazman on 3/6/2016.
*/
public class ImageSaver {
private String directoryName = "images";
private String fileName = "image.png";
private Context context;
private boolean external;
public ImageSaver(Context context) {
this.context = context;
}
public ImageSaver setFileName(String fileName) {
this.fileName = fileName;
return this;
}
public ImageSaver setExternal(boolean external) {
this.external = external;
return this;
}
public ImageSaver setDirectoryName(String directoryName) {
this.directoryName = directoryName;
return this;
}
public void save(Bitmap bitmapImage) {
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(createFile());
bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (fileOutputStream != null) {
fileOutputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
@NonNull
private File createFile() {
File directory;
if(external){
directory = getAlbumStorageDir(directoryName);
}
else {
directory = context.getDir(directoryName, Context.MODE_PRIVATE);
}
if(!directory.exists() && !directory.mkdirs()){
Log.e("ImageSaver","Error creating directory " + directory);
}
return new File(directory, fileName);
}
private File getAlbumStorageDir(String albumName) {
return new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), albumName);
}
public static boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
return Environment.MEDIA_MOUNTED.equals(state);
}
public static boolean isExternalStorageReadable() {
String state = Environment.getExternalStorageState();
return Environment.MEDIA_MOUNTED.equals(state) ||
Environment.MEDIA_MOUNTED_READ_ONLY.equals(state);
}
public Bitmap load() {
FileInputStream inputStream = null;
try {
inputStream = new FileInputStream(createFile());
return BitmapFactory.decodeStream(inputStream);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}
저장하려면 :
new ImageSaver(context).
setFileName("myImage.png").
setDirectoryName("images").
save(bitmap);
로드하려면
Bitmap bitmap = new ImageSaver(context).
setFileName("myImage.png").
setDirectoryName("images").
load();
편집하다:
Google 예제를ImageSaver.setExternal(boolean)
기반으로 외부 저장소에 저장을 지원하기 위해 추가되었습니다 .
public boolean deleteFile(){ File file = createFile(); return file.delete(); }
오늘이 질문에 왔으며 이것이 내가하는 방법입니다. 필요한 매개 변수를 사용 하여이 함수를 호출하십시오.
public void saveImage(Context context, Bitmap bitmap, String name, String extension){
name = name + "." + extension;
FileOutputStream fileOutputStream;
try {
fileOutputStream = context.openFileOutput(name, Context.MODE_PRIVATE);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fileOutputStream);
fileOutputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
마찬가지로, 같은 것을 읽으려면 이것을 사용하십시오
public Bitmap loadImageBitmap(Context context,String name,String extension){
name = name + "." + extension
FileInputStream fileInputStream
Bitmap bitmap = null;
try{
fileInputStream = context.openFileInput(name);
bitmap = BitmapFactory.decodeStream(fileInputStream);
fileInputStream.close();
} catch(Exception e) {
e.printStackTrace();
}
return bitmap;
}
b
함수에를 saveImage
. 내 안드로이드 장치에 이미지를 넣었지만 경로를 얻을 수 없습니다. 경로를 얻을 수 없으면 함수에 인수로 전달할 수 없습니다 saveImage
.
nil
그 사진을 읽으려고 할 때 항상 얻는다 .
Kotlin 사용자를 ImageStorageManager
위해 이미지에 대한 저장, 가져 오기 및 삭제 작업을 쉽게 처리 하는 클래스를 만들었습니다 .
class ImageStorageManager {
companion object {
fun saveToInternalStorage(context: Context, bitmapImage: Bitmap, imageFileName: String): String {
context.openFileOutput(imageFileName, Context.MODE_PRIVATE).use { fos ->
bitmapImage.compress(Bitmap.CompressFormat.PNG, 25, fos)
}
return context.filesDir.absolutePath
}
fun getImageFromInternalStorage(context: Context, imageFileName: String): Bitmap? {
val directory = context.filesDir
val file = File(directory, imageFileName)
return BitmapFactory.decodeStream(FileInputStream(file))
}
fun deleteImageFromInternalStorage(context: Context, imageFileName: String): Boolean {
val dir = context.filesDir
val file = File(dir, imageFileName)
return file.delete()
}
}
}
imageFileName
충분히를 검색합니다
public static String saveImage(String folderName, String imageName, RelativeLayout layoutCollage) {
String selectedOutputPath = "";
if (isSDCARDMounted()) {
File mediaStorageDir = new File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), folderName);
// Create a storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("PhotoEditorSDK", "Failed to create directory");
}
}
// Create a media file name
selectedOutputPath = mediaStorageDir.getPath() + File.separator + imageName;
Log.d("PhotoEditorSDK", "selected camera path " + selectedOutputPath);
File file = new File(selectedOutputPath);
try {
FileOutputStream out = new FileOutputStream(file);
if (layoutCollage != null) {
layoutCollage.setDrawingCacheEnabled(true);
layoutCollage.getDrawingCache().compress(Bitmap.CompressFormat.JPEG, 80, out);
}
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return selectedOutputPath;
}
private static boolean isSDCARDMounted() {
String status = Environment.getExternalStorageState();
return status.equals(Environment.MEDIA_MOUNTED);
}
// 다중 이미지 검색
File folPath = new File(getIntent().getStringExtra("folder_path"));
File[] imagep = folPath.listFiles();
for (int i = 0; i < imagep.length ; i++) {
imageModelList.add(new ImageModel(imagep[i].getAbsolutePath(), Uri.parse(imagep[i].getAbsolutePath())));
}
imagesAdapter.notifyDataSetChanged();
/data/data/yourapp/app_data/imageDir
정확히 어디에 ? stackoverflow.com/questions/40323126/…