Java Code Examples for android.os.ParcelFileDescriptor#getFileDescriptor()

The following examples show how to use android.os.ParcelFileDescriptor#getFileDescriptor() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PBitmapUtils.java    From YImagePicker with Apache License 2.0 6 votes vote down vote up
/**
 * 根据相对路径获取图片宽高
 *
 * @param c   上下文
 * @param uri 图片uri地址
 * @return 宽高信息
 */

public static int[] getImageWidthHeight(Context c, Uri uri) {
    try {
        ParcelFileDescriptor parcelFileDescriptor = c.getContentResolver()
                .openFileDescriptor(uri, "r");
        if (parcelFileDescriptor != null) {
            FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
            Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
            parcelFileDescriptor.close();
            return new int[]{image.getWidth(), image.getHeight()};
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return new int[]{0, 0};
}
 
Example 2
Source File: PBitmapUtils.java    From YImagePicker with Apache License 2.0 6 votes vote down vote up
public static Bitmap getBitmapFromUri(Context c, Uri uri) {
    try {
        ParcelFileDescriptor parcelFileDescriptor = c.getContentResolver()
                .openFileDescriptor(uri, "r");
        if (parcelFileDescriptor != null) {
            FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
            Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
            parcelFileDescriptor.close();
            return image;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}
 
Example 3
Source File: PBitmapUtils.java    From YImagePicker with Apache License 2.0 6 votes vote down vote up
/**
 * 根据相对路径获取图片宽高
 *
 * @param c   上下文
 * @param uri 图片uri地址
 * @return 宽高信息
 */

public static int[] getImageWidthHeight(Context c, Uri uri) {
    try {
        ParcelFileDescriptor parcelFileDescriptor = c.getContentResolver()
                .openFileDescriptor(uri, "r");
        if (parcelFileDescriptor != null) {
            FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
            Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
            parcelFileDescriptor.close();
            return new int[]{image.getWidth(), image.getHeight()};
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return new int[]{0, 0};
}
 
Example 4
Source File: StorageAccessHelper.java    From andOTP with MIT License 6 votes vote down vote up
public static boolean saveFile(Context context, Uri file, byte[] data) {
    boolean success = true;

    try {
        ParcelFileDescriptor pfd = context.getContentResolver().openFileDescriptor(file, "w");
        FileOutputStream fileOutputStream = new FileOutputStream(pfd.getFileDescriptor());

        fileOutputStream.write(data);

        fileOutputStream.close();
        pfd.close();
    } catch (IOException e) {
        e.printStackTrace();
        success = false;
    }

    return success;
}
 
Example 5
Source File: InstallHistoryActivity.java    From fdroidclient with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_install_history);
    Toolbar toolbar = findViewById(R.id.toolbar);
    toolbar.setTitle(getString(R.string.install_history));
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    String text = "";
    try {
        ContentResolver resolver = getContentResolver();

        Cursor cursor = resolver.query(InstallHistoryService.LOG_URI, null, null, null, null);
        if (cursor != null) {
            cursor.moveToFirst();
            cursor.close();
        }

        ParcelFileDescriptor pfd = resolver.openFileDescriptor(InstallHistoryService.LOG_URI, "r");
        FileDescriptor fd = pfd.getFileDescriptor();
        FileInputStream fileInputStream = new FileInputStream(fd);
        text = IOUtils.toString(fileInputStream, Charset.defaultCharset());
    } catch (IOException | SecurityException | IllegalStateException e) {
        e.printStackTrace();
    }
    TextView textView = findViewById(R.id.text);
    textView.setText(text);
}
 
Example 6
Source File: PictureMultiCuttingActivity.java    From Matisse-Kotlin with Apache License 2.0 6 votes vote down vote up
/**
 * This method extracts all data from the incoming intent and setups views properly.
 */
private void setImageData(@NonNull Intent intent) {
    Uri inputUri = intent.getParcelableExtra(UCropMulti.EXTRA_INPUT_URI);
    Uri outputUri = intent.getParcelableExtra(UCropMulti.EXTRA_OUTPUT_URI);
    processOptions(intent);

    if (inputUri != null && outputUri != null) {
        try {
            ParcelFileDescriptor parcelFileDescriptor = getContentResolver().openFileDescriptor(inputUri, "r");
            FileInputStream inputStream = new FileInputStream(parcelFileDescriptor.getFileDescriptor());
            String suffix = FileUtils.extSuffix(inputStream);
            boolean isGif = FileUtils.isGifForSuffix(suffix);
            mGestureCropImageView.setRotateEnabled(isGif ? false : rotateEnabled);
            mGestureCropImageView.setScaleEnabled(isGif ? false : scaleEnabled);
            mGestureCropImageView.setImageUri(inputUri, outputUri);
        } catch (Exception e) {
            setResultError(e);
            closeActivity();
        }
    } else {
        setResultError(new NullPointerException(getString(R.string.ucrop_error_input_data_is_absent)));
        closeActivity();
    }
}
 
Example 7
Source File: MiscUtil.java    From PLDroidShortVideo with Apache License 2.0 5 votes vote down vote up
public static Bitmap getBitmapFromUri(Context context, Uri uri) throws IOException {
    Logger(TAG, "getBitmapFromUri " + uri.toString(), false);
    ParcelFileDescriptor parcelFileDescriptor =
            context.getContentResolver().openFileDescriptor(uri, "r");
    FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
    Logger(TAG, "uri FileDescriptor : " + fileDescriptor.toString(), false);
    Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
    parcelFileDescriptor.close();
    return image;
}
 
Example 8
Source File: ChromeBackupAgent.java    From AndroidChromium with Apache License 2.0 5 votes vote down vote up
@SuppressFBWarnings(value = {"OS_OPEN_STREAM"}, justification = "Closed by backup system")
@SuppressWarnings("unchecked")
public BackupState(ParcelFileDescriptor parceledState) throws IOException {
    if (parceledState == null) return;
    try {
        FileInputStream instream = new FileInputStream(parceledState.getFileDescriptor());
        ObjectInputStream in = new ObjectInputStream(instream);
        mNames = (ArrayList<String>) in.readObject();
        mValues = (ArrayList<byte[]>) in.readObject();
    } catch (ClassNotFoundException e) {
        throw new RuntimeException(e);
    }
}
 
Example 9
Source File: TranslateActivity.java    From Stringlate with MIT License 5 votes vote down vote up
private void doExportToSd(Uri uri, File template)
        throws IOException {

    ParcelFileDescriptor pfd = getContentResolver().openFileDescriptor(uri, "w");
    FileOutputStream out = new FileOutputStream(pfd.getFileDescriptor());
    if (!mRepo.applyTemplate(template, mSelectedLocale, out))
        throw new IOException("Apply default template failed.");

    out.close();
    pfd.close();
}
 
Example 10
Source File: SafeContentResolver.java    From SafeContentResolver with Apache License 2.0 5 votes vote down vote up
/**
 * Open a stream to the content associated with a URI.
 *
 * <p>
 * If the provided URI is not a {@code file://} URI, {@link ContentResolver#openInputStream(Uri)} is used to open a
 * stream. If it is a {@code file://}, this method makes sure the file isn't owned by this app.
 * </p>
 *
 * @param uri
 *         The URI pointing to the content to access.
 *
 * @return {@code InputStream} to access the content.
 *
 * @throws FileNotFoundException
 *         If the provided URI could not be opened or if it points to a file owned by this app.
 */
@Nullable
public InputStream openInputStream(@NotNull Uri uri) throws FileNotFoundException {
    //noinspection ConstantConditions
    if (uri == null) {
        throw new NullPointerException("Argument 'uri' must not be null");
    }

    String scheme = uri.getScheme();
    if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
        String authority = uri.getAuthority();
        if (disallowedProviders.isDisallowed(authority)) {
            throw new FileNotFoundException("content URI is owned by the application itself. " +
                    "Content provider is not explicitly allowed: " + authority);
        }
    }

    if (!ContentResolver.SCHEME_FILE.equals(scheme)) {
        return contentResolver.openInputStream(uri);
    }

    File file = new File(uri.getPath());
    ParcelFileDescriptor parcelFileDescriptor = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
    FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();

    int fileUid = getFileUidOrThrow(fileDescriptor);
    if (fileUid == android.os.Process.myUid()) {
        throw new FileNotFoundException("File is owned by the application itself");
    }

    AssetFileDescriptor fd = new AssetFileDescriptor(parcelFileDescriptor, 0, -1);
    try {
        return fd.createInputStream();
    } catch (IOException e) {
        throw new FileNotFoundException("Unable to create stream");
    }
}
 
Example 11
Source File: ChromeBackupAgent.java    From AndroidChromium with Apache License 2.0 5 votes vote down vote up
@SuppressFBWarnings(value = {"OS_OPEN_STREAM"}, justification = "Closed by backup system")
public void save(ParcelFileDescriptor parceledState) throws IOException {
    FileOutputStream outstream = new FileOutputStream(parceledState.getFileDescriptor());
    ObjectOutputStream out = new ObjectOutputStream(outstream);
    out.writeObject(mNames);
    out.writeObject(mValues);
}
 
Example 12
Source File: ImageUtil.java    From ImageSelector with Apache License 2.0 5 votes vote down vote up
public static boolean isEffective(Context context, Uri uri) {
    try {
        ParcelFileDescriptor parcelFileDescriptor =
                context.getContentResolver().openFileDescriptor(uri, "r");
        FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options);
        return options.outWidth > 0 && options.outHeight > 0;
    } catch (IOException e) {
        e.printStackTrace();
    }
    return false;
}
 
Example 13
Source File: DownloadUriOutputStream.java    From okdownload with Apache License 2.0 5 votes vote down vote up
public DownloadUriOutputStream(Context context, Uri uri, int bufferSize) throws
        FileNotFoundException {
    final ParcelFileDescriptor pdf = context.getContentResolver().openFileDescriptor(uri, "rw");
    if (pdf == null) throw new FileNotFoundException("result of " + uri + " is null!");
    this.pdf = pdf;

    this.fos = new FileOutputStream(pdf.getFileDescriptor());
    this.channel = fos.getChannel();
    this.out = new BufferedOutputStream(fos, bufferSize);
}
 
Example 14
Source File: HostMediaPlayerManager.java    From DeviceConnect-Android with MIT License 5 votes vote down vote up
private FileDescriptor getDescriptorFromUri(final Uri uri) {
    ContentResolver resolver = getContentResolver();
    try {
        ParcelFileDescriptor descriptor =  resolver.openFileDescriptor(uri, "r");
        if (descriptor == null) {
            return null;
        }
        return descriptor.getFileDescriptor();
    } catch (IOException e) {
        return null;
    }
}
 
Example 15
Source File: ImageUtil.java    From YiBo with Apache License 2.0 5 votes vote down vote up
public static Bitmap scaleImageUriTo(ContentResolver resolver, Uri uri, int size) {
	if (resolver == null
		|| uri   == null
		|| size  <= 0) {
		return null;
	}

	ParcelFileDescriptor pfd;
	try {
	     pfd = resolver.openFileDescriptor(uri, "r");
	} catch (IOException e) {
		Logger.debug(e.getMessage(), e);
	    return null;
	}
	
	java.io.FileDescriptor fd = pfd.getFileDescriptor();
	BitmapFactory.Options options = new BitmapFactory.Options();

	//先指定原始大小
	options.inSampleSize = 1;
	//只进行大小判断
	options.inJustDecodeBounds = true;
	//调用此方法得到options得到图片的大小
	BitmapFactory.decodeFileDescriptor(fd, null, options);
	//获得缩放比例
	options.inSampleSize = getScaleSampleSize(options, size);
	//OK,我们得到了缩放的比例,现在开始正式读入BitMap数据
	options.inJustDecodeBounds = false;
	options.inDither = false;
	options.inPreferredConfig = Bitmap.Config.ARGB_8888;

	//根据options参数,减少所需要的内存
	Bitmap sourceBitmap = null;
	sourceBitmap = BitmapFactory.decodeFileDescriptor(fd, null, options);

	return sourceBitmap;
}
 
Example 16
Source File: DbBackupHelper.java    From trackworktime with GNU General Public License v3.0 5 votes vote down vote up
private void writeNewState(final long dbFileModification, final ParcelFileDescriptor newState) {
	// write to newState
	final FileOutputStream newStateOS = new FileOutputStream(newState.getFileDescriptor());
	final DataOutputStream newStateDataOS = new DataOutputStream(newStateOS);
	try {
		newStateDataOS.writeLong(dbFileModification);
		new WorkTimeTrackerBackupManager(context).setLastBackupTimestamp(dbFileModification);
		newStateDataOS.close();
	} catch (IOException e) {
		// error on writing the newState, ignored
	}
}
 
Example 17
Source File: SipSharedPreferencesHelper.java    From CSipSimple with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void writeNewStateDescription(ParcelFileDescriptor newState) {
    long fileModified = 0;
    if(prefsFiles != null) {
        prefsFiles.lastModified();
    }
    try {
        FileOutputStream outstream = new FileOutputStream(newState.getFileDescriptor());
        DataOutputStream out = new DataOutputStream(outstream);
        out.writeLong(fileModified);
        out.close();
    } catch (IOException e) {
        Log.e(THIS_FILE, "Cannot manage final local backup state", e);
    }
}
 
Example 18
Source File: MainActivity.java    From Legofy with Apache License 2.0 5 votes vote down vote up
private FileDescriptor getFileDescriptor(Uri uri) {
    ParcelFileDescriptor parcelFileDescriptor = null;
    try {
        parcelFileDescriptor = getContentResolver().openFileDescriptor(uri, "r");
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    return parcelFileDescriptor.getFileDescriptor();
}
 
Example 19
Source File: Util.java    From reader with MIT License 5 votes vote down vote up
public static Bitmap makeBitmap(int minSideLength, int maxNumOfPixels,
        Uri uri, ContentResolver cr, ParcelFileDescriptor pfd,
        BitmapFactory.Options options) {
    try {
        if (pfd == null) pfd = makeInputStream(uri, cr);
        if (pfd == null) return null;
        if (options == null) options = new BitmapFactory.Options();

        FileDescriptor fd = pfd.getFileDescriptor();
        options.inJustDecodeBounds = true;
        BitmapManager.instance().decodeFileDescriptor(fd, options);
        if (options.mCancel || options.outWidth == -1
                || options.outHeight == -1) {
            return null;
        }
        options.inSampleSize = computeSampleSize(
                options, minSideLength, maxNumOfPixels);
        options.inJustDecodeBounds = false;

        options.inDither = false;
        options.inPreferredConfig = Bitmap.Config.ARGB_8888;
        return BitmapManager.instance().decodeFileDescriptor(fd, options);
    } catch (OutOfMemoryError ex) {
        Log.e(TAG, "Got oom exception ", ex);
        return null;
    } finally {
        closeSilently(pfd);
    }
}
 
Example 20
Source File: MediaStoreOutputStream.java    From libcommon with Apache License 2.0 5 votes vote down vote up
/**
 * コンストラクタ
 * @param context
 * @param mimeType
 * @param relativePath
 * @param nameWithExt
 * @param dataPath
 * @throws FileNotFoundException
 */
public MediaStoreOutputStream(@NonNull final Context context,
	@Nullable final String mimeType,
	@Nullable final String relativePath,
	@NonNull final String nameWithExt,
	@Nullable final String dataPath)
		throws FileNotFoundException {

	mCr = context.getContentResolver();
	mUri = MediaStoreUtils.getContentUri(mCr, mimeType, relativePath, nameWithExt, dataPath);
	final ParcelFileDescriptor pfd = mCr.openFileDescriptor(mUri, "rw");
	mOutputStream = new FileOutputStream(pfd.getFileDescriptor());
	mOutputPath = UriHelper.getPath(context, mUri);
}