Skip to content

Commit

Permalink
Add support for Uri data uris.
Browse files Browse the repository at this point in the history
Previously we only supported data uris if they were provided as Strings.

Fixes #556.
  • Loading branch information
sjudd committed Feb 5, 2018
1 parent e60c451 commit 17c1c3d
Show file tree
Hide file tree
Showing 4 changed files with 125 additions and 14 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
package com.bumptech.glide;

import static com.google.common.truth.Truth.assertThat;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import android.util.Base64;
import com.bumptech.glide.test.ConcurrencyHelper;
import com.bumptech.glide.test.ResourceIds;
import com.bumptech.glide.test.TearDownGlide;
import java.io.ByteArrayOutputStream;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;

@RunWith(AndroidJUnit4.class)
public class DataUriTest {
@Rule public TearDownGlide tearDownGlide = new TearDownGlide();
private final ConcurrencyHelper concurrency = new ConcurrencyHelper();
private final Context context = InstrumentationRegistry.getTargetContext();

@Test
public void load_withJpegAsDataUriString_returnsBitmap() {
Bitmap bitmap =
concurrency.get(
Glide.with(context)
.asBitmap()
.load(getDataUriString(CompressFormat.JPEG))
.submit());
assertThat(bitmap).isNotNull();
}

@Test
public void load_withPngDataUriString_returnsBitmap() {
Bitmap bitmap =
concurrency.get(
Glide.with(context)
.asBitmap()
.load(getDataUriString(CompressFormat.PNG))
.submit());
assertThat(bitmap).isNotNull();
}

@Test
public void load_withJpegAsDataUri_returnsBitmap() {
Bitmap bitmap =
concurrency.get(
Glide.with(context)
.asBitmap()
.load(getDataUri(CompressFormat.JPEG))
.submit());
assertThat(bitmap).isNotNull();
}

@Test
public void load_withPngAsDataUri_returnsBitmap() {
Bitmap bitmap =
concurrency.get(
Glide.with(context)
.asBitmap()
.load(getDataUri(CompressFormat.PNG))
.submit());
assertThat(bitmap).isNotNull();
}

private Uri getDataUri(CompressFormat format) {
return Uri.parse(getDataUriString(format));
}

private String getDataUriString(CompressFormat format) {
String bytes = getBase64BitmapBytes(format);
String imageType;
switch (format) {
case PNG:
imageType = "png";
break;
case JPEG:
imageType = "jpeg";
break;
case WEBP:
imageType = "webp";
break;
default:
throw new IllegalArgumentException("Unrecognized format: " + format);
}

String mimeType = "image/" + imageType;
return "data:" + mimeType + ";base64," + bytes;
}

private String getBase64BitmapBytes(CompressFormat format) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
Drawable drawable = context.getResources().getDrawable(ResourceIds.raw.canonical);
Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
bitmap.compress(format, 100, bos);
byte[] data = bos.toByteArray();
return Base64.encodeToString(data, /*flags=*/ 0);
}
}
3 changes: 2 additions & 1 deletion library/src/main/java/com/bumptech/glide/Glide.java
Original file line number Diff line number Diff line change
Expand Up @@ -446,7 +446,8 @@ Uri.class, Bitmap.class, new ResourceBitmapDecoder(resourceDrawableDecoder, bitm
AssetFileDescriptor.class,
resourceLoaderAssetFileDescriptorFactory)
.append(int.class, Uri.class, resourceLoaderUriFactory)
.append(String.class, InputStream.class, new DataUrlLoader.StreamFactory())
.append(String.class, InputStream.class, new DataUrlLoader.StreamFactory<String>())
.append(Uri.class, InputStream.class, new DataUrlLoader.StreamFactory<Uri>())
.append(String.class, InputStream.class, new StringLoader.StreamFactory())
.append(String.class, ParcelFileDescriptor.class, new StringLoader.FileDescriptorFactory())
.append(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,10 @@
*
* <p>Briefly, a 'data' URL has the form: <pre>data:[mediatype][;base64],some_data</pre>
*
* @param <Data> The type of data that can be opened.
* @param <Model> The type of Model that we can retrieve data for, e.g. {@link String}.
* @param <Data> The type of data that can be opened, e.g. {@link InputStream}.
*/
public final class DataUrlLoader<Data> implements ModelLoader<String, Data> {
public final class DataUrlLoader<Model, Data> implements ModelLoader<Model, Data> {

private static final String DATA_SCHEME_IMAGE = "data:image";
private static final String BASE64_TAG = ";base64";
Expand All @@ -35,14 +36,17 @@ public DataUrlLoader(DataDecoder<Data> dataDecoder) {
}

@Override
public LoadData<Data> buildLoadData(@NonNull String model, int width, int height,
public LoadData<Data> buildLoadData(@NonNull Model model, int width, int height,
@NonNull Options options) {
return new LoadData<>(new ObjectKey(model), new DataUriFetcher<>(model, dataDecoder));
return new LoadData<>(
new ObjectKey(model), new DataUriFetcher<>(model.toString(), dataDecoder));
}

@Override
public boolean handles(@NonNull String url) {
return url.startsWith(DATA_SCHEME_IMAGE);
public boolean handles(@NonNull Model model) {
// We expect Model to be a Uri or a String, both of which implement toString() efficiently. We
// should reconsider this implementation before adding any new Model types.
return model.toString().startsWith(DATA_SCHEME_IMAGE);
}

/**
Expand Down Expand Up @@ -108,9 +112,11 @@ public DataSource getDataSource() {
}

/**
* Factory for loading {@link InputStream} from Data URL string.
* Factory for loading {@link InputStream}s from data uris.
*
* @param <Model> The type of Model we can obtain data for, e.g. String.
*/
public static final class StreamFactory implements ModelLoaderFactory<String, InputStream> {
public static final class StreamFactory<Model> implements ModelLoaderFactory<Model, InputStream> {

private final DataDecoder<InputStream> opener;

Expand Down Expand Up @@ -152,7 +158,7 @@ public Class<InputStream> getDataClass() {

@NonNull
@Override
public ModelLoader<String, InputStream> build(
public ModelLoader<Model, InputStream> build(
@NonNull MultiModelLoaderFactory multiFactory) {
return new DataUrlLoader<>(opener);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,18 +56,17 @@ public class DataUrlLoaderTest {

@Mock
private MultiModelLoaderFactory multiFactory;
private DataUrlLoader<InputStream> dataUrlLoader;
private DataUrlLoader<String, InputStream> dataUrlLoader;
private DataFetcher<InputStream> fetcher;
private Options options;

@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
DataUrlLoader.StreamFactory factory = new DataUrlLoader.StreamFactory();
DataUrlLoader.StreamFactory<String> factory = new DataUrlLoader.StreamFactory<>();
options = new Options();
dataUrlLoader = (DataUrlLoader<InputStream>) factory.build(multiFactory);
dataUrlLoader = (DataUrlLoader<String, InputStream>) factory.build(multiFactory);
fetcher = dataUrlLoader.buildLoadData(VALID_PNG, -1, -1, options).fetcher;

}

@Test
Expand Down

0 comments on commit 17c1c3d

Please sign in to comment.