Android Сохранение созданного растрового изображения в каталог на SD-карте
Я создал растровое изображение, и теперь я хочу сохранить это растровое изображение в директории где-нибудь. Может ли кто-нибудь показать мне, как это делается. Благодаря
FileInputStream in;
BufferedInputStream buf;
try {
in = new FileInputStream("/mnt/sdcard/dcim/Camera/2010-11-16_18-57-18_989.jpg");
buf = new BufferedInputStream(in);
Bitmap _bitmapPreScale = BitmapFactory.decodeStream(buf);
int oldWidth = _bitmapPreScale.getWidth();
int oldHeight = _bitmapPreScale.getHeight();
int newWidth = 2592;
int newHeight = 1936;
float scaleWidth = ((float) newWidth) / oldWidth;
float scaleHeight = ((float) newHeight) / oldHeight;
Matrix matrix = new Matrix();
// resize the bit map
matrix.postScale(scaleWidth, scaleHeight);
Bitmap _bitmapScaled = Bitmap.createBitmap(_bitmapPreScale, 0, 0, oldWidth, oldHeight, matrix, true);
(Я хочу сохранить _bitmapScaled в папку на моей SD-карте)
Ответы
Ответ 1
Привет. Вы можете записать данные в байты, а затем создать файл в папке sdcard с любым именем и расширением, а затем записать байты в этот файл.
Это сохранит растровое изображение на SD-карте.
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
_bitmapScaled.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
//you can create a new file name "test.jpg" in sdcard folder.
File f = new File(Environment.getExternalStorageDirectory()
+ File.separator + "test.jpg");
f.createNewFile();
//write the bytes in file
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
// remember close de FileOutput
fo.close();
Ответ 2
Вы также можете попробовать это.
OutputStream fOut = null;
File file = new File(strDirectoy,imgname);
fOut = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, fOut);
fOut.flush();
fOut.close();
MediaStore.Images.Media.insertImage(getContentResolver(),file.getAbsolutePath(),file.getName(),file.getName());
Ответ 3
_bitmapScaled.compress()
должен сделать трюк. Проверьте документы: http://developer.android.com/reference/android/graphics/Bitmap.html#compress(android.graphics.Bitmap.CompressFormat, int, java.io.OutputStream)
Ответ 4
просто измените расширение на .bmp.
Сделай это:
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
_bitmapScaled.compress(Bitmap.CompressFormat.PNG, 40, bytes);
//you can create a new file name "test.BMP" in sdcard folder.
File f = new File(Environment.getExternalStorageDirectory()
+ File.separator + "test.bmp")
Будет звучать, что я просто дурачусь, но попробуйте один раз, и он будет сохранен в формате BMP
. Ура!
Ответ 5
Этот ответ представляет собой обновление с немного большим вниманием к OOM и другим утечкам.
Предположим, что у вас есть каталог, предназначенный для адресата, и имя, которое уже определено.
File destination = new File(directory.getPath() + File.separatorChar + filename);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
source.compress(Bitmap.CompressFormat.PNG, 100, bytes);
FileOutputStream fo = null;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
} catch (IOException e) {
} finally {
try {
fo.close();
} catch (IOException e) {}
}
Ответ 6
Передайте растровое изображение в метод saveImage, оно сохранит ваше растровое изображение под именем saveBitmap внутри созданной тестовой папки.
private void saveImage(Bitmap data) {
File createFolder = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),"test");
if(!createFolder.exists())
createFolder.mkdir();
File saveImage = new File(createFolder,"saveBitmap.jpg");
try {
OutputStream outputStream = new FileOutputStream(saveImage);
data.compress(Bitmap.CompressFormat.JPEG,100,outputStream);
outputStream.flush();
outputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
и используйте это:
saveImage(bitmap);