developer tip

드로어 블에 저장된 이미지의 URI 가져 오기

copycodes 2021. 1. 5. 08:13
반응형

드로어 블에 저장된 이미지의 URI 가져 오기


사용자가 처음 볼 때 너무 빈 것처럼 보이지 않도록 응용 프로그램에 몇 가지 샘플 항목을 추가하고 있습니다. 샘플 항목이 포함 된 목록에는 이미지가 있어야하며 사용할 이미지는 이미 응용 프로그램의 / res / drawable-folder에 저장되어 있습니다.

이미 URI에서 항목 이미지를로드하는 메서드가 있으므로 /res/drawable/myImage.jpg에 대한 URI를 가져오고 싶지만 올바르게 가져올 수없는 것 같습니다.

흐름은 다음과 같습니다. 이미지의 URI를 나타내는 문자열로 항목을 만듭니다. 목록에 항목 목록 보내기 목록은 문자열을 URL로 변환하여 백그라운드 작업에서 이미지를로드 한 다음 url.openStream ();을 실행합니다.

성공하지 못한 채 URI에 대한 몇 가지 옵션을 시도했습니다. "android.resource : // ....."는 알 수없는 프로토콜 "file : //"파일을 찾을 수 없음을 나타냅니다.

그래서 지금은이 문제를 해결하는 방법에 대해 조금 잃어 버렸습니다 ..


ContentResolver리소스 URI를 여는 데 사용해야 합니다.

Uri uri = Uri.parse("android.resource://your.package.here/drawable/image_name");
InputStream stream = getContentResolver().openInputStream(uri);

또한이 방법을 사용하여 파일 및 콘텐츠 URI를 열 수 있습니다.


/**
 * get uri to drawable or any other resource type if u wish 
 * @param context - context
 * @param drawableId - drawable res id
 * @return - uri 
 */
public static final Uri getUriToDrawable(@NonNull Context context, 
                                         @AnyRes int drawableId) {
    Uri imageUri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE +
            "://" + context.getResources().getResourcePackageName(drawableId)
            + '/' + context.getResources().getResourceTypeName(drawableId)
            + '/' + context.getResources().getResourceEntryName(drawableId) );
    return imageUri;
}

위를 기반으로-모든 리소스에 대해 조정 된 버전 :

 /**
 * get uri to any resource type
 * @param context - context
 * @param resId - resource id
 * @throws Resources.NotFoundException if the given ID does not exist.
 * @return - Uri to resource by given id 
 */
public static final Uri getUriToResource(@NonNull Context context, 
                                         @AnyRes int resId)
                           throws Resources.NotFoundException {
    /** Return a Resources instance for your application's package. */
    Resources res = context.getResources();
    /**
     * Creates a Uri which parses the given encoded URI string.
     * @param uriString an RFC 2396-compliant, encoded URI
     * @throws NullPointerException if uriString is null
     * @return Uri for this given uri string
     */
    Uri resUri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE +
            "://" + res.getResourcePackageName(resId)
            + '/' + res.getResourceTypeName(resId)
            + '/' + res.getResourceEntryName(resId));
    /** return uri */
    return resUri;
}

몇 가지 정보 :

From the Java Language spec.:

"17.5 Final Field Semantics

... when the object is seen by another thread, that thread will always
see the correctly constructed version of that object's final fields.
It will also see versions of any object or array referenced by
those final fields that are at least as up-to-date as the final fields
are."

In that same vein, all non-transient fields within Uri
implementations should be final and immutable so as to ensure true
immutability for clients even when they don't use proper concurrency
control.

For reference, from RFC 2396:

"4.3. Parsing a URI Reference

   A URI reference is typically parsed according to the four main
   components and fragment identifier in order to determine what
   components are present and whether the reference is relative or
   absolute.  The individual components are then parsed for their
   subparts and, if not opaque, to verify their validity.

   Although the BNF defines what is allowed in each component, it is
   ambiguous in terms of differentiating between an authority component
   and a path component that begins with two slash characters.  The
   greedy algorithm is used for disambiguation: the left-most matching
   rule soaks up as much of the URI reference string as it is capable of
   matching.  In other words, the authority component wins."

...

3. URI Syntactic Components

   The URI syntax is dependent upon the scheme.  
   In general, absolute URI are written as follows:

     <scheme>:<scheme-specific-part>

   An absolute URI contains the name of the scheme being used (<scheme>)
   followed by a colon (":") and then a string  (the <scheme-specific-part>) 
   whose interpretation depends on the scheme.

   The URI syntax does not require that the scheme-specific-part have any
   general structure or set of semantics which is common among all URI.
   However, a subset of URI do share a common syntax for representing
   hierarchical relationships within the namespace.  This "generic URI"
   syntax consists of a sequence of four main components:

     <scheme>://<authority><path>?<query>

출처 :

분쟁

이 답변은 정확하지만 최종 필드에 대한 부분은 아닙니다. 답변과 관련이 없습니다 – Boris Treukhov

@BorisTreukhov- "최종 필드에 대한 부분이 정확하지 않습니다"가 의미하는 바를 자세히 설명해주세요-질문-URI 를 ...로 가져 오는 방법? 구문 분석 할 수있는 방식을 구성하십시오 (uri는 어떻게 구문 분석됩니까? 답변 참조).

package android.net;

/**
 * Immutable URI reference. A URI reference includes a URI and a fragment, the
 * component of the URI following a '#'. Builds and parses URI references
 * which conform to
 * <a href="http://www.faqs.org/rfcs/rfc2396.html">RFC 2396</a>.
 *
 * <p>In the interest of performance, this class performs little to no
 * validation. Behavior is undefined for invalid input. This class is very
 * forgiving--in the face of invalid input, it will return garbage
 * rather than throw an exception unless otherwise specified.
 */
 public abstract class Uri implements Parcelable, Comparable<Uri> { ... }

This is what you really need:

 Uri imageUri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE +
 "://" + getResources().getResourcePackageName(R.drawable.ic_launcher)
 + '/' + getResources().getResourceTypeName(R.drawable.ic_launcher) + '/' + getResources().getResourceEntryName(R.drawable.ic_launcher) );

You can use Uri.Builder instead of string concatenation

 Uri imageUri = (new Uri.Builder())
    .scheme(ContentResolver.SCHEME_ANDROID_RESOURCE)
    .authority(resources.getResourcePackageName(resourceId))
    .appendPath(resources.getResourceTypeName(resourceId))
    .appendPath(resources.getResourceEntryName(resourceId))
    .build()

The easiest answer would be: Uri.parse(String goes here); //So, to make the drawable fit inside that bracket you just need to do this.

Uri.parse(getResource().getDrawable(R.drawable.ic_launcher_background).toString());

That's it.

ReferenceURL : https://stackoverflow.com/questions/6602417/get-the-uri-of-an-image-stored-in-drawable

반응형