1 /* 2 * Copyright (C) 2017 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 package com.android.managedprovisioning.common; 17 18 import android.graphics.Bitmap; 19 import android.graphics.Color; 20 import android.net.Uri; 21 22 import java.io.File; 23 import java.io.FileOutputStream; 24 import java.io.IOException; 25 26 /** 27 * Test helper class to simplify testing cases where drawables are handled as Uri's. 28 */ 29 public class UriBitmap { 30 private final Bitmap mBitmap; 31 private final Uri mUri; 32 private final File mTempFile; 33 UriBitmap(Bitmap bitmap, Uri uri, File tempFile)34 private UriBitmap(Bitmap bitmap, Uri uri, File tempFile) { 35 mBitmap = bitmap; 36 mUri = uri; 37 mTempFile = tempFile; 38 } 39 getBitmap()40 public Bitmap getBitmap() { 41 return mBitmap; 42 } 43 getUri()44 public Uri getUri() { 45 return mUri; 46 } 47 48 /** 49 * @return an instance encapsulating a sample {@link Bitmap} and a {@link Uri} pointing to it 50 */ createSimpleInstance()51 public static UriBitmap createSimpleInstance() throws IOException { 52 Bitmap bitmap = generateSampleBitmap(); 53 File tempFile = File.createTempFile("tmpImage", ".png"); 54 Uri uri = bitmapToUri(bitmap, tempFile); 55 return new UriBitmap(bitmap, uri, tempFile); 56 } 57 generateSampleBitmap()58 private static Bitmap generateSampleBitmap() { 59 Bitmap bitmap = Bitmap.createBitmap(15, 15, Bitmap.Config.ARGB_8888); 60 for (int x = 0; x < bitmap.getWidth(); x++) { 61 for (int y = 0; y < bitmap.getHeight(); y++) { 62 bitmap.setPixel(x, y, Color.rgb(x, y, x + y)); 63 } 64 } 65 return bitmap; 66 } 67 bitmapToUri(Bitmap bitmap, File tempFile)68 private static Uri bitmapToUri(Bitmap bitmap, File tempFile) throws IOException { 69 try (FileOutputStream fs = new FileOutputStream(tempFile)) { 70 bitmap.compress(Bitmap.CompressFormat.PNG, 100, fs); 71 return Uri.fromFile(tempFile); 72 } 73 } 74 75 /** 76 * Deletes the temp file where the image is stored (simple way to generate an Uri-enabled image) 77 */ 78 @Override finalize()79 protected void finalize() throws Throwable { 80 if (mTempFile != null) { 81 //noinspection ResultOfMethodCallIgnored 82 mTempFile.delete(); 83 } 84 super.finalize(); 85 } 86 }