App/Android
Android image 저장
selfstarter
2020. 7. 22. 23:14
android의 공용path에 image 저장
1) Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) 으로 DCIM 폴더 위치 가져오기. 여기서 내가 생성할 폴더 이름을 추가하고 폴더를 생성한다.(DCIM폴더는 사진, 동영상을 저장하는 폴더)
2) 파일 객체를 생성하고 파일이름이 중복되었는지 체크한다. 중복이라면 실패
3) 파일에 쓸 output Stream을 생성
4) bitmap을 resize해서 새로운 bitmap을 만든다
5) compress함수로 bitmap을 PNG로 변경하고 결과를 output stream에 저장한다,
6) output stream을 닫는다
지금 확인해보니 이미지가 엄청 깨지는건 이미지 resize일 때 문제였다. 수정필요..
public boolean saveImage(Bitmap bitmap, String saveImageName) {
String saveDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).toString()+ "/directoryName";
File file = new File(saveDir);
if (!file.exists()) {
file.mkdir();
}
String fileName = saveImageName + ".png";
File tempFile = new File(saveDir, fileName);
FileOutputStream output = null;
try {
if (tempFile.createNewFile()) {
output = new FileOutputStream(tempFile);
// 이미지 줄이기
// TODO : 사진 비율로 압축하도록 수정할 것
Bitmap newBitmap = bitmap.createScaledBitmap(bitmap, 200, 200, true);
// 이미지 압축. 압축된 파일은 output stream에 저장. 2번째 인자는 압축률인데 100으로 해도 많이 깨진다..
newBitmap.compress(Bitmap.CompressFormat.PNG, 100, output);
} else {
// 같은 이름의 파일 존재
Log.d("TEST_LOG", "같은 이름의 파일 존재:"+saveImageName);
return false;
}
} catch (FileNotFoundException e) {
Log.d("TEST_LOG", "파일을 찾을 수 없음");
return false;
} catch (IOException e) {
Log.d("TEST_LOG", "IO 에러");
e.printStackTrace();
return false;
} finally {
if (output != null) {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return true;
}
saveImage 함수는 이렇게 호출한다
imageSaveBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (imageView == null) {
return;
}
saveImage(((BitmapDrawable) imageView.getDrawable()).getBitmap(), simpleDateFormat.format(new Date()));
}
});