1/* 2 * Copyright (C) 2010 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 17package com.android.apps.tag.record; 18 19import com.android.apps.tag.R; 20import com.google.common.base.Preconditions; 21 22import android.app.Activity; 23import android.graphics.Bitmap; 24import android.graphics.BitmapFactory; 25import android.nfc.NdefRecord; 26import android.view.LayoutInflater; 27import android.view.View; 28import android.view.ViewGroup; 29import android.widget.ImageView; 30 31import java.io.ByteArrayOutputStream; 32 33/** 34 * A NdefRecord corresponding to an image type. 35 */ 36public class ImageRecord extends ParsedNdefRecord { 37 38 public static final String RECORD_TYPE = "ImageRecord"; 39 40 private final Bitmap mBitmap; 41 42 private ImageRecord(Bitmap bitmap) { 43 mBitmap = Preconditions.checkNotNull(bitmap); 44 } 45 46 @Override 47 public View getView(Activity activity, LayoutInflater inflater, ViewGroup parent, int offset) { 48 ImageView image = (ImageView) inflater.inflate(R.layout.tag_image, parent, false); 49 image.setImageBitmap(mBitmap); 50 return image; 51 } 52 53 public static ImageRecord parse(NdefRecord record) { 54 String mimeType = record.toMimeType(); 55 if (mimeType == null) { 56 throw new IllegalArgumentException("not a valid image file"); 57 } 58 Preconditions.checkArgument(mimeType.startsWith("image/")); 59 60 // Try to ensure it's a legal, valid image 61 byte[] content = record.getPayload(); 62 Bitmap bitmap = BitmapFactory.decodeByteArray(content, 0, content.length); 63 if (bitmap == null) { 64 throw new IllegalArgumentException("not a valid image file"); 65 } 66 return new ImageRecord(bitmap); 67 } 68 69 public static boolean isImage(NdefRecord record) { 70 try { 71 parse(record); 72 return true; 73 } catch (IllegalArgumentException e) { 74 return false; 75 } 76 } 77 78 public static NdefRecord newImageRecord(Bitmap bitmap) { 79 ByteArrayOutputStream out = new ByteArrayOutputStream(); 80 bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out); 81 byte[] content = out.toByteArray(); 82 return NdefRecord.createMime("image/jpeg", content); 83 } 84} 85