Java Code Examples for android.content.ContentResolver#openInputStream()

The following examples show how to use android.content.ContentResolver#openInputStream() . 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: Global.java    From Favorite-Android-Client with Apache License 2.0 6 votes vote down vote up
public static InputStream editIMGSize(ContentResolver cr, Uri uri)
		throws FileNotFoundException {
	int[] size = new int[2];
	Bitmap bm;
	InputStream in = cr.openInputStream(uri);
	BitmapFactory.Options option = new BitmapFactory.Options();
	option.inPurgeable = true;
	option.inJustDecodeBounds = true;
	// BitmapFactory.decodeStream(in, null, option);
	bm = BitmapFactory.decodeStream(in, null, option);
	// 1is height
	size[1] = option.outHeight;
	size[0] = option.outWidth;
	//
	// if(editsize == true){
	if (size[1] > 4000)
		option.inSampleSize = 2;
	if (size[1] > 1024)
		option.inSampleSize = 4;
	// }
	//
	return in;

}
 
Example 2
Source File: UtteranceRewriter.java    From speechutils with Apache License 2.0 6 votes vote down vote up
/**
 * Loads the rewrites from an URI using a ContentResolver.
 * The first line is a header.
 * Non-header lines are ignored if they start with '#'.
 */
private static CommandHolder loadRewrites(ContentResolver contentResolver, Uri uri) throws IOException {
    CommandHolder commandHolder = null;
    InputStream inputStream = contentResolver.openInputStream(uri);
    if (inputStream != null) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        String line = reader.readLine();
        if (line != null) {
            int lineCounter = 0;
            commandHolder = new CommandHolder(line);
            while ((line = reader.readLine()) != null) {
                lineCounter++;
                commandHolder.addLine(line, lineCounter, null);
            }
        }
        inputStream.close();
    }
    if (commandHolder == null) {
        return new CommandHolder();
    }
    return commandHolder;
}
 
Example 3
Source File: ContactsPhotoRequestHandler.java    From DoraemonKit with Apache License 2.0 6 votes vote down vote up
private InputStream getInputStream(Request data) throws IOException {
  ContentResolver contentResolver = context.getContentResolver();
  Uri uri = data.uri;
  switch (matcher.match(uri)) {
    case ID_LOOKUP:
      uri = ContactsContract.Contacts.lookupContact(contentResolver, uri);
      if (uri == null) {
        return null;
      }
      // Resolved the uri to a contact uri, intentionally fall through to process the resolved uri
    case ID_CONTACT:
      if (SDK_INT < ICE_CREAM_SANDWICH) {
        return openContactPhotoInputStream(contentResolver, uri);
      } else {
        return ContactPhotoStreamIcs.get(contentResolver, uri);
      }
    case ID_THUMBNAIL:
    case ID_DISPLAY_PHOTO:
      return contentResolver.openInputStream(uri);
    default:
      throw new IllegalStateException("Invalid uri: " + uri);
  }
}
 
Example 4
Source File: BitmapUtils.java    From giffun with Apache License 2.0 6 votes vote down vote up
/**
 * Decode image from uri using given "inSampleSize", but if failed due to out-of-memory then raise
 * the inSampleSize until success.
 */
private static Bitmap decodeImage(
    ContentResolver resolver, Uri uri, BitmapFactory.Options options)
    throws FileNotFoundException {
  do {
    InputStream stream = null;
    try {
      stream = resolver.openInputStream(uri);
      return BitmapFactory.decodeStream(stream, EMPTY_RECT, options);
    } catch (OutOfMemoryError e) {
      options.inSampleSize *= 2;
    } finally {
      closeSafe(stream);
    }
  } while (options.inSampleSize <= 512);
  throw new RuntimeException("Failed to decode image: " + uri);
}
 
Example 5
Source File: PreviewFragment.java    From kolabnotes-android with GNU Lesser General Public License v3.0 6 votes vote down vote up
void displayText(ActiveAccount account, String noteUID,Attachment attachment){
    textView.setVisibility(View.VISIBLE);

    if(android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
        ContentResolver contentResolver = getActivity().getContentResolver();
        Uri uri = attachmentRepository.getUriFromAttachment(account.getAccount(), account.getRootFolder(), noteUID, attachment);


        try(BufferedReader reader = new BufferedReader(new InputStreamReader(contentResolver.openInputStream(uri)))){

            StringBuilder text = new StringBuilder();
            String  line;
            while((line =reader.readLine()) != null){
                text.append(line);
                text.append(System.lineSeparator());
            }

            textView.setText(text);
        } catch (IOException e) {
            Log.e("displayText","Exception while opening file:",e);
        }
    }
}
 
Example 6
Source File: BaseImageDownloader.java    From mobile-manager-tool with MIT License 6 votes vote down vote up
/**
 * Retrieves {@link java.io.InputStream} of image by URI (image is accessed using {@link android.content.ContentResolver}).
 *
 * @param imageUri Image URI
 * @param extra    Auxiliary object which was passed to {@link com.nostra13.universalimageloader.core.DisplayImageOptions.Builder#extraForDownloader(Object)
 *                 DisplayImageOptions.extraForDownloader(Object)}; can be null
 * @return {@link java.io.InputStream} of image
 * @throws java.io.FileNotFoundException if the provided URI could not be opened
 */
protected InputStream getStreamFromContent(String imageUri, Object extra) throws FileNotFoundException {
	ContentResolver res = context.getContentResolver();

	Uri uri = Uri.parse(imageUri);
	if (isVideoUri(uri)) { // video thumbnail
		Long origId = Long.valueOf(uri.getLastPathSegment());
		Bitmap bitmap = MediaStore.Video.Thumbnails
				.getThumbnail(res, origId, MediaStore.Images.Thumbnails.MINI_KIND, null);
		if (bitmap != null) {
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			bitmap.compress(CompressFormat.PNG, 0, bos);
			return new ByteArrayInputStream(bos.toByteArray());
		}
	} else if (imageUri.startsWith(CONTENT_CONTACTS_URI_PREFIX)) { // contacts photo
		return ContactsContract.Contacts.openContactPhotoInputStream(res, uri);
	}

	return res.openInputStream(uri);
}
 
Example 7
Source File: BitmapUtil.java    From MVPAndroidBootstrap with Apache License 2.0 6 votes vote down vote up
/**
 * Get width and height of the bitmap specified with the {@link android.net.Uri}.
 *
 * @param resolver the resolver.
 * @param uri      the uri that points to the bitmap.
 * @return the size.
 */
public static Point getSize(ContentResolver resolver, Uri uri) {
    InputStream is = null;
    try {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        is = resolver.openInputStream(uri);
        BitmapFactory.decodeStream(is, null, options);
        int width = options.outWidth;
        int height = options.outHeight;
        return new Point(width, height);
    } catch (FileNotFoundException e) {
        Log.e(TAG, "target file (" + uri + ") does not exist.", e);
        return null;
    } finally {
        CloseableUtils.close(is);
    }
}
 
Example 8
Source File: PolicyManagementFragment.java    From android-testdpc with Apache License 2.0 6 votes vote down vote up
/**
 * Imports a CA certificate from the given data URI.
 *
 * @param intent Intent that contains the CA data URI.
 */
private void importCaCertificateFromIntent(Intent intent) {
    if (getActivity() == null || getActivity().isFinishing()) {
        return;
    }
    Uri data = null;
    if (intent != null && (data = intent.getData()) != null) {
        ContentResolver cr = getActivity().getContentResolver();
        boolean isCaInstalled = false;
        try {
            InputStream certificateInputStream = cr.openInputStream(data);
            isCaInstalled = Util.installCaCertificate(certificateInputStream,
                    mDevicePolicyManager, mAdminComponentName);
        } catch (FileNotFoundException e) {
            Log.e(TAG, "importCaCertificateFromIntent: ", e);
        }
        showToast(isCaInstalled ? R.string.install_ca_successfully : R.string.install_ca_fail);
    }
}
 
Example 9
Source File: BitmapUtils.java    From framework with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Read bytes.
 *
 * @param uri      the uri
 * @param resolver the resolver
 * @return the byte[]
 * @throws IOException Signals that an I/O exception has occurred.
 */
private static byte[] readBytes(Uri uri, ContentResolver resolver, boolean thumbnail)
        throws IOException {
    // this dynamically extends to take the bytes you read
    InputStream inputStream = resolver.openInputStream(uri);
    ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();

    if (!thumbnail) {
        // this is storage overwritten on each iteration with bytes
        int bufferSize = 1024;
        byte[] buffer = new byte[bufferSize];

        // we need to know how may bytes were read to write them to the
        // byteBuffer
        int len = 0;
        while ((len = inputStream.read(buffer)) != -1) {
            byteBuffer.write(buffer, 0, len);
        }
    } else {
        Bitmap imageBitmap = BitmapFactory.decodeStream(inputStream);
        int thumb_width = imageBitmap.getWidth() / 2;
        int thumb_height = imageBitmap.getHeight() / 2;
        if (thumb_width > THUMBNAIL_SIZE) {
            thumb_width = THUMBNAIL_SIZE;
        }
        if (thumb_width == THUMBNAIL_SIZE) {
            thumb_height = ((imageBitmap.getHeight() / 2) * THUMBNAIL_SIZE)
                    / (imageBitmap.getWidth() / 2);
        }
        imageBitmap = Bitmap.createScaledBitmap(imageBitmap, thumb_width, thumb_height, false);
        imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteBuffer);
    }
    // and then we can return your byte array.
    return byteBuffer.toByteArray();
}
 
Example 10
Source File: ImageUtils_Deprecated.java    From UltimateAndroid with Apache License 2.0 5 votes vote down vote up
/**
 * 解析Bitmap的公用方法.
 *
 * @param path
 * @param data
 * @param context
 * @param uri
 * @param options
 * @return
 */
public static Bitmap decode(String path, byte[] data, Context context,
                            Uri uri, BitmapFactory.Options options) {

    Bitmap result = null;

    if (path != null) {

        result = BitmapFactory.decodeFile(path, options);

    } else if (data != null) {

        result = BitmapFactory.decodeByteArray(data, 0, data.length,
                options);

    } else if (uri != null) {
        //uri不为空的时候context也不要为空.
        ContentResolver cr = context.getContentResolver();
        InputStream inputStream = null;

        try {
            inputStream = cr.openInputStream(uri);
            result = BitmapFactory.decodeStream(inputStream, null, options);
            inputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    return result;
}
 
Example 11
Source File: Base.java    From indigenous-android with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Get file data from uri or bitmap.
 */
public byte[] getFileData(Bitmap bitmap, Boolean scale, Uri uri, String mime) {

    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

    if (scale) {
        int ImageQuality = 80;
        // Default quality. The preference is stored as a string, but cast it to an integer.
        String qualityPreference = Preferences.getPreference(this, "pref_key_image_quality", Integer.toString(ImageQuality));
        if (parseInt(qualityPreference) <= 100 && parseInt(qualityPreference) > 0) {
            ImageQuality = parseInt(qualityPreference);
        }

        switch (mime) {
            case "image/png":
                bitmap.compress(Bitmap.CompressFormat.PNG, ImageQuality, byteArrayOutputStream);
                break;
            case "image/jpg":
            default:
                bitmap.compress(Bitmap.CompressFormat.JPEG, ImageQuality, byteArrayOutputStream);
                break;
        }
    }
    else {
        ContentResolver cR = this.getContentResolver();
        try {
            InputStream is = cR.openInputStream(uri);
            final byte[] b = new byte[8192];
            for (int r; (r = is.read(b)) != -1;) {
                byteArrayOutputStream.write(b, 0, r);
            }
        }
        catch (Exception ignored) { }
    }

    return byteArrayOutputStream.toByteArray();
}
 
Example 12
Source File: loveviayou.java    From styT with Apache License 2.0 5 votes vote down vote up
public static InputStream GetISfromIntent(Intent u, Activity con) {
    ContentResolver cr = con.getContentResolver();
    try {
        return cr.openInputStream(u.getData());
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        return null;
    }

}
 
Example 13
Source File: ImageLoader.java    From BigApp_Discuz_Android with Apache License 2.0 5 votes vote down vote up
/**
 * From Content
 *
 * @param imageUri
 * @param imageView
 * @throws IOException
 */
protected void displayImageFromContent(String imageUri, ImageView imageView) throws FileNotFoundException {
    ContentResolver res = context.getContentResolver();
    Uri uri = Uri.parse(imageUri);
    InputStream inputStream = res.openInputStream(uri);
    Bitmap bitmap = BitmapUtils.loadFromInputStream(inputStream, null);
    imageView.setImageBitmap(bitmap);

    return;
}
 
Example 14
Source File: BitmapUtils.java    From giffun with Apache License 2.0 5 votes vote down vote up
/** Decode image from uri using "inJustDecodeBounds" to get the image dimensions. */
private static BitmapFactory.Options decodeImageForOption(ContentResolver resolver, Uri uri)
    throws FileNotFoundException {
  InputStream stream = null;
  try {
    stream = resolver.openInputStream(uri);
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeStream(stream, EMPTY_RECT, options);
    options.inJustDecodeBounds = false;
    return options;
  } finally {
    closeSafe(stream);
  }
}
 
Example 15
Source File: MediaStoreContent.java    From DeviceConnect-Android with MIT License 4 votes vote down vote up
@Override
public InputStream open(final Context context) throws IOException {
    ContentResolver resolver = context.getContentResolver();
    return resolver.openInputStream(mMediaUri);
}
 
Example 16
Source File: SkiaImageDecoder.java    From RxTools-master with Apache License 2.0 4 votes vote down vote up
@Override
public Bitmap decode(Context context, Uri uri) throws Exception {
    String uriString = uri.toString();
    BitmapFactory.Options options = new BitmapFactory.Options();
    Bitmap bitmap;
    options.inPreferredConfig = Bitmap.Config.RGB_565;
    if (uriString.startsWith(RESOURCE_PREFIX)) {
        Resources res;
        String packageName = uri.getAuthority();
        if (context.getPackageName().equals(packageName)) {
            res = context.getResources();
        } else {
            PackageManager pm = context.getPackageManager();
            res = pm.getResourcesForApplication(packageName);
        }

        int id = 0;
        List<String> segments = uri.getPathSegments();
        int size = segments.size();
        if (size == 2 && segments.get(0).equals("drawable")) {
            String resName = segments.get(1);
            id = res.getIdentifier(resName, "drawable", packageName);
        } else if (size == 1 && TextUtils.isDigitsOnly(segments.get(0))) {
            try {
                id = Integer.parseInt(segments.get(0));
            } catch (NumberFormatException ignored) {
            }
        }

        bitmap = BitmapFactory.decodeResource(context.getResources(), id, options);
    } else if (uriString.startsWith(ASSET_PREFIX)) {
        String assetName = uriString.substring(ASSET_PREFIX.length());
        bitmap = BitmapFactory.decodeStream(context.getAssets().open(assetName), null, options);
    } else if (uriString.startsWith(FILE_PREFIX)) {
        bitmap = BitmapFactory.decodeFile(uriString.substring(FILE_PREFIX.length()), options);
    } else {
        InputStream inputStream = null;
        try {
            ContentResolver contentResolver = context.getContentResolver();
            inputStream = contentResolver.openInputStream(uri);
            bitmap = BitmapFactory.decodeStream(inputStream, null, options);
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (Exception e) {
                }
            }
        }
    }
    if (bitmap == null) {
        throw new RuntimeException("Skia image region decoder returned null bitmap - image format may not be supported");
    }
    return bitmap;
}
 
Example 17
Source File: MainFragment.java    From openinwa with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void onStart() {
    Intent intent = getActivity().getIntent();
    String action = intent.getAction();
    if (Intent.ACTION_SEND.equals(action)) {
        String type = intent.getType();
        if ("text/x-vcard".equals(type)) {
            isShare = true;
            Uri contactUri = intent.getParcelableExtra(Intent.EXTRA_STREAM);
            ContentResolver cr;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
                cr = this.getContext().getContentResolver();
            else cr = getActivity().getContentResolver();

            String data = "";
            try {
                InputStream stream = cr.openInputStream(contactUri);
                StringBuffer fileContent = new StringBuffer("");
                int ch;
                while ((ch = stream.read()) != -1)
                    fileContent.append((char) ch);
                stream.close();
                data = new String(fileContent);

            } catch (Exception e) {
                e.printStackTrace();
            }

            for (String line : data.split("\n")) {
                line = line.trim();
                //todo: support other phone numbers from vcard
                if (line.startsWith("TEL;CELL:")) {
                    number = line.substring(9);
                    mPhoneInput.setPhoneNumber(number);
                }
            }
        }
    } else if (Intent.ACTION_DIAL.equals(action)) {
        number = intent.getData().toString().substring(3);
        Log.d(MainFragment.class.getName(), "onStart: number==" + number);
        mPhoneInput.setPhoneNumber(number);
    }
    super.onStart();
}
 
Example 18
Source File: SkiaImageRegionDecoder.java    From subsampling-scale-image-view with Apache License 2.0 4 votes vote down vote up
@Override
@NonNull
public Point init(Context context, @NonNull Uri uri) throws Exception {
    String uriString = uri.toString();
    if (uriString.startsWith(RESOURCE_PREFIX)) {
        Resources res;
        String packageName = uri.getAuthority();
        if (context.getPackageName().equals(packageName)) {
            res = context.getResources();
        } else {
            PackageManager pm = context.getPackageManager();
            res = pm.getResourcesForApplication(packageName);
        }

        int id = 0;
        List<String> segments = uri.getPathSegments();
        int size = segments.size();
        if (size == 2 && segments.get(0).equals("drawable")) {
            String resName = segments.get(1);
            id = res.getIdentifier(resName, "drawable", packageName);
        } else if (size == 1 && TextUtils.isDigitsOnly(segments.get(0))) {
            try {
                id = Integer.parseInt(segments.get(0));
            } catch (NumberFormatException ignored) {
            }
        }

        decoder = BitmapRegionDecoder.newInstance(context.getResources().openRawResource(id), false);
    } else if (uriString.startsWith(ASSET_PREFIX)) {
        String assetName = uriString.substring(ASSET_PREFIX.length());
        decoder = BitmapRegionDecoder.newInstance(context.getAssets().open(assetName, AssetManager.ACCESS_RANDOM), false);
    } else if (uriString.startsWith(FILE_PREFIX)) {
        decoder = BitmapRegionDecoder.newInstance(uriString.substring(FILE_PREFIX.length()), false);
    } else {
        InputStream inputStream = null;
        try {
            ContentResolver contentResolver = context.getContentResolver();
            inputStream = contentResolver.openInputStream(uri);
            if (inputStream == null) {
                throw new Exception("Content resolver returned null stream. Unable to initialise with uri.");
            }
            decoder = BitmapRegionDecoder.newInstance(inputStream, false);
        } finally {
            if (inputStream != null) {
                try { inputStream.close(); } catch (Exception e) { /* Ignore */ }
            }
        }
    }
    return new Point(decoder.getWidth(), decoder.getHeight());
}
 
Example 19
Source File: SkiaImageDecoder.java    From PictureSelector with Apache License 2.0 4 votes vote down vote up
@Override
public Bitmap decode(Context context, Uri uri) throws Exception {
    String uriString = uri.toString();
    BitmapFactory.Options options = new BitmapFactory.Options();
    Bitmap bitmap;
    options.inPreferredConfig = Bitmap.Config.RGB_565;
    if (uriString.startsWith(RESOURCE_PREFIX)) {
        Resources res;
        String packageName = uri.getAuthority();
        if (context.getPackageName().equals(packageName)) {
            res = context.getResources();
        } else {
            PackageManager pm = context.getPackageManager();
            res = pm.getResourcesForApplication(packageName);
        }

        int id = 0;
        List<String> segments = uri.getPathSegments();
        int size = segments.size();
        if (size == 2 && segments.get(0).equals("drawable")) {
            String resName = segments.get(1);
            id = res.getIdentifier(resName, "drawable", packageName);
        } else if (size == 1 && TextUtils.isDigitsOnly(segments.get(0))) {
            try {
                id = Integer.parseInt(segments.get(0));
            } catch (NumberFormatException ignored) {
            }
        }

        bitmap = BitmapFactory.decodeResource(context.getResources(), id, options);
    } else if (uriString.startsWith(ASSET_PREFIX)) {
        String assetName = uriString.substring(ASSET_PREFIX.length());
        bitmap = BitmapFactory.decodeStream(context.getAssets().open(assetName), null, options);
    } else if (uriString.startsWith(FILE_PREFIX)) {
        bitmap = BitmapFactory.decodeFile(uriString.substring(FILE_PREFIX.length()), options);
    } else {
        InputStream inputStream = null;
        try {
            ContentResolver contentResolver = context.getContentResolver();
            inputStream = contentResolver.openInputStream(uri);
            bitmap = BitmapFactory.decodeStream(inputStream, null, options);
        } finally {
            if (inputStream != null) {
                try { inputStream.close(); } catch (Exception e) { }
            }
        }
    }
    if (bitmap == null) {
        throw new RuntimeException("Skia image region decoder returned null bitmap - image format may not be supported");
    }
    return bitmap;
}
 
Example 20
Source File: BaseImageDownloader.java    From Roid-Library with Apache License 2.0 2 votes vote down vote up
/**
 * Retrieves {@link InputStream} of image by URI (image is accessed using
 * {@link ContentResolver}).
 * 
 * @param imageUri Image URI
 * @param extra Auxiliary object which was passed to
 *            {@link DisplayImageOptions.Builder#extraForDownloader(Object)
 *            DisplayImageOptions.extraForDownloader(Object)}; can be null
 * @return {@link InputStream} of image
 * @throws FileNotFoundException if the provided URI could not be opened
 */
protected InputStream getStreamFromContent(String imageUri, Object extra) throws FileNotFoundException {
    ContentResolver res = context.getContentResolver();
    Uri uri = Uri.parse(imageUri);
    return res.openInputStream(uri);
}