下面列出了android.content.ContentResolver#openOutputStream ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public void addNewHoardWithImage(int rowId, Bitmap hoardImage) {
// Create a URI addressing a specific row.
Uri rowURI =
ContentUris.withAppendedId(MyHoardContentProvider.CONTENT_URI, rowId);
// Get the Content Resolver
ContentResolver cr = getContentResolver();
try {
// Open an output stream using the row's URI.
OutputStream outStream = cr.openOutputStream(rowURI);
// Compress your bitmap and save it into your provider.
hoardImage.compress(Bitmap.CompressFormat.JPEG, 80, outStream);
} catch (FileNotFoundException e) {
Log.d(TAG, "No file found for this record.");
}
}
public static OutputStream getOutputStream(final Context c, final Uri u)
{
try
{
ContentResolver cr = c.getContentResolver();
OutputStream os = cr.openOutputStream(u);
ViewUtils.Debug(c, "writing uri: " + u.toString());
if (os != null)
{
return os;
}
}
catch (Exception e)
{
final String error = String.format(c.getResources().getString(R.string.error_file_write),
u.getLastPathSegment());
ViewUtils.Debug(c, error + ", " + e.getLocalizedMessage());
Toast.makeText(c, error, Toast.LENGTH_LONG).show();
}
return null;
}
static boolean copyFileOntoRemovableStorage(Context context, Uri treeUri,
String path, String destination) throws IOException {
String mimeType = MediaType.getMimeType(path);
DocumentFile file = DocumentFile.fromFile(new File(destination));
if (file.exists()) {
int index = destination.lastIndexOf(".");
destination = destination.substring(0, index) + " Copy"
+ destination.substring(index, destination.length());
}
DocumentFile destinationFile = StorageUtil.createDocumentFile(context, treeUri, destination, mimeType);
if (destinationFile != null) {
ContentResolver resolver = context.getContentResolver();
OutputStream outputStream = resolver.openOutputStream(destinationFile.getUri());
InputStream inputStream = new FileInputStream(path);
return writeStream(inputStream, outputStream);
}
return false;
}
public static boolean saveBitmap(ContentResolver contentResolver, Uri uri, Bitmap bitmap,
Bitmap.CompressFormat format, int quality) {
OutputStream outputStream;
try {
outputStream = contentResolver.openOutputStream(uri);
} catch (FileNotFoundException e) {
Timber.d(e, "[saveBitmap] Couldn't open uri output");
return false;
}
boolean saveOk = true;
try {
bitmap.compress(format, quality, outputStream);
} finally {
if (!close(outputStream)) {
saveOk = false;
}
}
if (!saveOk) {
contentResolver.delete(uri, null, null);
}
return saveOk;
}
/**
* {@inheritDoc}
*/
@Override
public void exportGeoPackage(String database, Uri uri, ContentValues contentValues) throws IOException {
// Get the GeoPackage database file
File dbFile = getFile(database);
// Insert the row
ContentResolver resolver = context.getContentResolver();
Uri insertUri = resolver.insert(uri, contentValues);
// Copy the GeoPackage file
OutputStream outputStream = resolver.openOutputStream(insertUri);
InputStream inputStream = new FileInputStream(dbFile);
GeoPackageIOUtils.copyStream(inputStream, outputStream);
}
public static boolean saveBitmap(ContentResolver contentResolver, Uri uri, Bitmap bitmap,
Bitmap.CompressFormat format, int quality) {
OutputStream outputStream;
try {
outputStream = contentResolver.openOutputStream(uri);
} catch (FileNotFoundException e) {
Timber.d(e, "[saveBitmap] Couldn't open uri output");
return false;
}
boolean saveOk = true;
try {
bitmap.compress(format, quality, outputStream);
} finally {
if (!close(outputStream)) {
saveOk = false;
}
}
if (!saveOk) {
contentResolver.delete(uri, null, null);
}
return saveOk;
}
public static String saveBitmapAndroidQ(Context context, String dir, Bitmap b) {
long dataTake = System.currentTimeMillis();
String jpegName = "IMG_" + dataTake + ".jpg";
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.DISPLAY_NAME, jpegName);
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
values.put(MediaStore.Images.Media.RELATIVE_PATH, "DCIM/" + dir);
Uri external;
ContentResolver resolver = context.getContentResolver();
String status = Environment.getExternalStorageState();
// 判断是否有SD卡,优先使用SD卡存储,当没有SD卡时使用手机存储
if (status.equals(Environment.MEDIA_MOUNTED)) {
external = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else {
external = MediaStore.Images.Media.INTERNAL_CONTENT_URI;
}
Uri insertUri = resolver.insert(external, values);
if (insertUri == null) {
return "";
}
OutputStream os;
try {
os = resolver.openOutputStream(insertUri);
b.compress(Bitmap.CompressFormat.JPEG, 100, os);
if (os != null) {
os.flush();
os.close();
}
return insertUri.toString();
} catch (IOException e) {
e.printStackTrace();
return "";
}
}
public static void copy(ContentResolver resolver, Uri source, Uri dest, OnCopyListener listener) throws IOException {
FileInputStream in = null;
OutputStream out = null;
try{
AssetFileDescriptor fd = resolver.openAssetFileDescriptor(source, "r");
in = fd != null ? fd.createInputStream() : null;
if (in == null){
throw new IOException("open the src file failed");
}
long total = fd.getLength();
long sum = 0;
out = resolver.openOutputStream(dest);
if (out == null) {
throw new IOException("open the dest file failed");
}
// Transfer bytes from in to out
byte[] buf = new byte[1024 * 4];
int len;
Thread thread = Thread.currentThread();
while ((len = in.read(buf)) > 0) {
if (thread.isInterrupted()) {
break;
}
sum += len;
out.write(buf, 0, len);
if (listener != null) {
listener.inProgress(sum * 1.0f / total);
}
}
}finally {
IOUtil.closeQuiet(in);
IOUtil.closeQuiet(out);
}
}
@TargetApi(29)
private static OutputStream openNewDownloadOutputStreamQ(
@NonNull final Context context,
@NonNull final String fileName,
@NonNull final String mimeType) throws IOException {
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DISPLAY_NAME, fileName);
values.put(MediaStore.MediaColumns.MIME_TYPE, mimeType);
ContentResolver resolver = context.getContentResolver();
Uri targetFileUri = resolver.insert(MediaStore.Downloads.EXTERNAL_CONTENT_URI, values);
if (null == targetFileUri) throw new IOException("Target URI could not be formed");
return resolver.openOutputStream(targetFileUri);
}
private void shotOneTextViaMediaStore() {
try {
final String pic_file_path;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
pic_file_path = Environment.DIRECTORY_PICTURES + File.separator + "OneText" + File.separator;
} else {
pic_file_path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + File.separator + "OneText" + File.separator;
}
final String pic_file_name = "OneText " + System.currentTimeMillis() + ".jpg";
Bitmap bitmap = SaveBitmapUtil.getCacheBitmapFromView(pic_layout);
ContentResolver resolver = getContentResolver();
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DISPLAY_NAME, pic_file_name);
values.put(MediaStore.Images.Media.DATE_ADDED, System.currentTimeMillis());
values.put(MediaStore.MediaColumns.MIME_TYPE, "image/jpeg");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
values.put(MediaStore.MediaColumns.RELATIVE_PATH, pic_file_path);
} else {
File path = new File(pic_file_path);
//noinspection ResultOfMethodCallIgnored
path.mkdirs();
values.put(MediaStore.MediaColumns.DATA, path + File.separator + pic_file_name);
}
final Uri imageUri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
if (imageUri != null) {
OutputStream stream = resolver.openOutputStream(imageUri);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
if (stream != null) {
stream.close();
}
}
Snackbar.make(rootview, getString(R.string.save_succeed) + " " + pic_file_name, Snackbar.LENGTH_SHORT).setAction(R.string.share_text, new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_STREAM, imageUri);
intent.setType("image/*");
startActivity(Intent.createChooser(intent, getString(R.string.share_text)));
}
}).show();
} catch (Exception e) {
Snackbar.make(rootview, getString(R.string.save_fail), Snackbar.LENGTH_SHORT).show();
}
}
private static void saveBitmapAndroidQ(Activity act, String dir, Bitmap b, final SaveBitmapCallBack callBack) {
long dataTake = System.currentTimeMillis();
String jpegName = "IMG_" + dataTake + ".jpg";
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.DISPLAY_NAME, jpegName);
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
values.put(MediaStore.Images.Media.RELATIVE_PATH, "DCIM/" + dir);
Uri external;
ContentResolver resolver = act.getContentResolver();
String status = Environment.getExternalStorageState();
// 判断是否有SD卡,优先使用SD卡存储,当没有SD卡时使用手机存储
if (status.equals(Environment.MEDIA_MOUNTED)) {
external = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else {
external = MediaStore.Images.Media.INTERNAL_CONTENT_URI;
}
final Uri insertUri = resolver.insert(external, values);
if (insertUri == null) {
act.runOnUiThread(new Runnable() {
@Override
public void run() {
callBack.onCreateDirFailed();
}
});
return;
}
OutputStream os;
try {
os = resolver.openOutputStream(insertUri);
b.compress(Bitmap.CompressFormat.JPEG, 100, os);
if (os != null) {
os.flush();
os.close();
}
act.runOnUiThread(new Runnable() {
@Override
public void run() {
callBack.onSuccess(insertUri.toString());
}
});
} catch (final IOException e) {
e.printStackTrace();
act.runOnUiThread(new Runnable() {
@Override
public void run() {
callBack.onFailed(e);
}
});
}
}
/**
* Storing image to device gallery
*
* @param cr
* @param source
* @param title
* @param description
* @return
*/
public static final String insertImage(ContentResolver cr,
Bitmap source,
String title,
String description) {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, title);
values.put(MediaStore.Images.Media.DISPLAY_NAME, title);
values.put(MediaStore.Images.Media.DESCRIPTION, description);
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
// Add the date meta data to ensure the image is added at the front of the gallery
values.put(MediaStore.Images.Media.DATE_ADDED, System.currentTimeMillis());
values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis());
Uri url = null;
String stringUrl = null; /* value to be returned */
try {
url = cr.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
if (source != null) {
OutputStream imageOut = cr.openOutputStream(url);
try {
source.compress(Bitmap.CompressFormat.JPEG, 50, imageOut);
} finally {
imageOut.close();
}
long id = ContentUris.parseId(url);
// Wait until MINI_KIND thumbnail is generated.
Bitmap miniThumb = MediaStore.Images.Thumbnails.getThumbnail(cr, id, MediaStore.Images.Thumbnails.MINI_KIND, null);
// This is for backward compatibility.
storeThumbnail(cr, miniThumb, id, 50F, 50F, MediaStore.Images.Thumbnails.MICRO_KIND);
} else {
cr.delete(url, null, null);
url = null;
}
} catch (Exception e) {
if (url != null) {
cr.delete(url, null, null);
url = null;
}
}
if (url != null) {
stringUrl = url.toString();
}
return stringUrl;
}
public static final String insertImage(ContentResolver cr,
Bitmap source,
String title,
String description) {
ContentValues values = new ContentValues();
values.put(Images.Media.TITLE, title);
values.put(Images.Media.DISPLAY_NAME, title);
values.put(Images.Media.DESCRIPTION, description);
values.put(Images.Media.MIME_TYPE, "image/jpeg");
// Add the date meta data to ensure the image is added at the front of the gallery
values.put(Images.Media.DATE_ADDED, System.currentTimeMillis());
values.put(Images.Media.DATE_TAKEN, System.currentTimeMillis());
Uri url = null;
String stringUrl = null; /* value to be returned */
try {
url = cr.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
if (source != null) {
OutputStream imageOut = cr.openOutputStream(url);
try {
source.compress(Bitmap.CompressFormat.JPEG, 50, imageOut);
} finally {
imageOut.close();
}
long id = ContentUris.parseId(url);
// Wait until MINI_KIND thumbnail is generated.
Bitmap miniThumb = Images.Thumbnails.getThumbnail(cr, id, Images.Thumbnails.MINI_KIND, null);
// This is for backward compatibility.
storeThumbnail(cr, miniThumb, id, 50F, 50F,Images.Thumbnails.MICRO_KIND);
} else {
cr.delete(url, null, null);
url = null;
}
} catch (Exception e) {
if (url != null) {
cr.delete(url, null, null);
url = null;
}
}
if (url != null) {
stringUrl = url.toString();
}
return stringUrl;
}
public static final String insertImage(ContentResolver cr,
Bitmap source,
String title,
String description) {
ContentValues values = new ContentValues();
values.put(Images.Media.TITLE, title);
values.put(Images.Media.DISPLAY_NAME, title);
values.put(Images.Media.DESCRIPTION, description);
values.put(Images.Media.MIME_TYPE, "image/jpeg");
// Add the date meta data to ensure the image is added at the front of the gallery
values.put(Images.Media.DATE_ADDED, System.currentTimeMillis());
values.put(Images.Media.DATE_TAKEN, System.currentTimeMillis());
Uri url = null;
String stringUrl = null; /* value to be returned */
try {
url = cr.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
//url = cr.insert(Uri.fromFile(dir), values);
if (source != null) {
OutputStream imageOut = cr.openOutputStream(url);
try {
source.compress(Bitmap.CompressFormat.JPEG, 50, imageOut);
} finally {
imageOut.close();
}
long id = ContentUris.parseId(url);
// Wait until MINI_KIND thumbnail is generated.
Bitmap miniThumb = Images.Thumbnails.getThumbnail(cr, id, Images.Thumbnails.MINI_KIND, null);
// This is for backward compatibility.
storeThumbnail(cr, miniThumb, id, 50F, 50F,Images.Thumbnails.MICRO_KIND);
} else {
cr.delete(url, null, null);
url = null;
}
} catch (Exception e) {
if (url != null) {
cr.delete(url, null, null);
url = null;
}
}
if (url != null) {
stringUrl = url.toString();
}
return stringUrl;
}
public static final String insertImage(ContentResolver cr,
Bitmap source,
String title,
String description) {
ContentValues values = new ContentValues();
values.put(Images.Media.TITLE, title);
values.put(Images.Media.DISPLAY_NAME, title);
values.put(Images.Media.DESCRIPTION, description);
values.put(Images.Media.MIME_TYPE, "image/jpeg");
// Add the date meta data to ensure the image is added at the front of the gallery
values.put(Images.Media.DATE_ADDED, System.currentTimeMillis());
values.put(Images.Media.DATE_TAKEN, System.currentTimeMillis());
Uri url = null;
String stringUrl = null; /* value to be returned */
try {
url = cr.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
if (source != null) {
OutputStream imageOut = cr.openOutputStream(url);
try {
source.compress(Bitmap.CompressFormat.JPEG, 50, imageOut);
} finally {
imageOut.close();
}
long id = ContentUris.parseId(url);
// Wait until MINI_KIND thumbnail is generated.
Bitmap miniThumb = Images.Thumbnails.getThumbnail(cr, id, Images.Thumbnails.MINI_KIND, null);
// This is for backward compatibility.
storeThumbnail(cr, miniThumb, id, 50F, 50F,Images.Thumbnails.MICRO_KIND);
} else {
cr.delete(url, null, null);
url = null;
}
} catch (Exception e) {
if (url != null) {
cr.delete(url, null, null);
url = null;
}
}
if (url != null) {
stringUrl = url.toString();
}
return stringUrl;
}
public static final String insertImage(ContentResolver cr,
Bitmap source,
String title,
String description) {
ContentValues values = new ContentValues();
values.put(Images.Media.TITLE, title);
values.put(Images.Media.DISPLAY_NAME, title);
values.put(Images.Media.DESCRIPTION, description);
values.put(Images.Media.MIME_TYPE, "image/jpeg");
// Add the date meta data to ensure the image is added at the front of the gallery
values.put(Images.Media.DATE_ADDED, System.currentTimeMillis());
values.put(Images.Media.DATE_TAKEN, System.currentTimeMillis());
Uri url = null;
String stringUrl = null; /* value to be returned */
try {
url = cr.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
//url = cr.insert(Uri.fromFile(dir), values);
if (source != null) {
OutputStream imageOut = cr.openOutputStream(url);
try {
source.compress(Bitmap.CompressFormat.JPEG, 50, imageOut);
} finally {
imageOut.close();
}
long id = ContentUris.parseId(url);
// Wait until MINI_KIND thumbnail is generated.
Bitmap miniThumb = Images.Thumbnails.getThumbnail(cr, id, Images.Thumbnails.MINI_KIND, null);
// This is for backward compatibility.
storeThumbnail(cr, miniThumb, id, 50F, 50F,Images.Thumbnails.MICRO_KIND);
} else {
cr.delete(url, null, null);
url = null;
}
} catch (Exception e) {
if (url != null) {
cr.delete(url, null, null);
url = null;
}
}
if (url != null) {
stringUrl = url.toString();
}
return stringUrl;
}
/**
* @param cr The content resolver
* @param source the bitmap source file
* @param title the title in string
* @param description the description in string
* @param cb optional additional call back
* @return the string in return
*/
@TargetApi(Build.VERSION_CODES.ECLAIR)
public static final String insertImage(ContentResolver cr,
Bitmap source,
String title,
String description,
Callback cb) {
ContentValues values = new ContentValues();
values.put(Images.Media.TITLE, title);
values.put(Images.Media.DISPLAY_NAME, title);
values.put(Images.Media.DESCRIPTION, description);
values.put(Images.Media.MIME_TYPE, "image/jpeg");
// Add the date meta data to ensure the image is added at the front of the gallery
values.put(Images.Media.DATE_ADDED, System.currentTimeMillis());
values.put(Images.Media.DATE_TAKEN, System.currentTimeMillis());
Uri url = null;
String stringUrl = null; /* value to be returned */
try {
url = cr.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
if (source != null) {
OutputStream imageOut = cr.openOutputStream(url);
try {
source.compress(Bitmap.CompressFormat.JPEG, 50, imageOut);
} finally {
imageOut.close();
}
long id = ContentUris.parseId(url);
// Wait until MINI_KIND thumbnail is generated.
Bitmap miniThumb = Images.Thumbnails.getThumbnail(cr, id, Images.Thumbnails.MINI_KIND, null);
// This is for backward compatibility.
storeThumbnail(cr, miniThumb, id, 50F, 50F, Images.Thumbnails.MICRO_KIND);
} else {
cr.delete(url, null, null);
url = null;
}
} catch (Exception e) {
if (url != null) {
cr.delete(url, null, null);
url = null;
}
}
if (url != null) {
stringUrl = url.toString();
}
if (cb != null) {
cb.complete();
}
return stringUrl;
}
/**
* A copy of the Android internals insertImage method, this method populates the
* meta data with DATE_ADDED and DATE_TAKEN. This fixes a common problem where media
* that is inserted manually gets saved at the end of the gallery (because date is not populated).
* @see android.provider.MediaStore.Images.Media#insertImage(ContentResolver, Bitmap, String, String)
*/
public static final String insertImage(ContentResolver cr,
Bitmap source,
String title,
String description) {
ContentValues values = new ContentValues();
values.put(Images.Media.TITLE, title);
values.put(Images.Media.DISPLAY_NAME, title);
values.put(Images.Media.DESCRIPTION, description);
values.put(Images.Media.MIME_TYPE, "image/jpeg");
// Add the date meta data to ensure the image is added at the front of the gallery
values.put(Images.Media.DATE_ADDED, System.currentTimeMillis());
values.put(Images.Media.DATE_TAKEN, System.currentTimeMillis());
Uri url = null;
String stringUrl = null; /* value to be returned */
try {
url = cr.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
if (source != null) {
OutputStream imageOut = cr.openOutputStream(url);
try {
source.compress(Bitmap.CompressFormat.JPEG, 50, imageOut);
} finally {
imageOut.close();
}
long id = ContentUris.parseId(url);
// Wait until MINI_KIND thumbnail is generated.
Bitmap miniThumb = Images.Thumbnails.getThumbnail(cr, id, Images.Thumbnails.MINI_KIND, null);
// This is for backward compatibility.
storeThumbnail(cr, miniThumb, id, 50F, 50F,Images.Thumbnails.MICRO_KIND);
} else {
cr.delete(url, null, null);
url = null;
}
} catch (Exception e) {
if (url != null) {
cr.delete(url, null, null);
url = null;
}
}
if (url != null) {
stringUrl = url.toString();
}
return stringUrl;
}