blob: dae3caf6c5708d50d011eda5094c1cf5bdd61435 [file] [log] [blame]
George Mount387d45d2011-10-07 15:57:53 -07001/*
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 */
Bijan Amirzada41242f22014-03-21 12:12:18 -070016package com.android.browser;
George Mount387d45d2011-10-07 15:57:53 -070017
18import java.net.MalformedURLException;
19
Bijan Amirzada9b1e9882014-02-26 17:15:46 -080020import android.util.Base64;
George Mount387d45d2011-10-07 15:57:53 -070021/**
22 * Class extracts the mime type and data from a data uri.
23 * A data URI is of the form:
24 * <pre>
25 * data:[&lt;MIME-type&gt;][;charset=&lt;encoding&gt;][;base64],&lt;data&gt;
26 * </pre>
27 */
28public class DataUri {
29 private static final String DATA_URI_PREFIX = "data:";
30 private static final String BASE_64_ENCODING = ";base64";
31
32 private String mMimeType;
33 private byte[] mData;
34
35 public DataUri(String uri) throws MalformedURLException {
36 if (!isDataUri(uri)) {
37 throw new MalformedURLException("Not a data URI");
38 }
39
40 int commaIndex = uri.indexOf(',', DATA_URI_PREFIX.length());
41 if (commaIndex < 0) {
42 throw new MalformedURLException("Comma expected in data URI");
43 }
44 String contentType = uri.substring(DATA_URI_PREFIX.length(),
45 commaIndex);
46 mData = uri.substring(commaIndex + 1).getBytes();
47 if (contentType.contains(BASE_64_ENCODING)) {
Bijan Amirzada9b1e9882014-02-26 17:15:46 -080048 mData = Base64.decode(mData, Base64.DEFAULT);
George Mount387d45d2011-10-07 15:57:53 -070049 }
50 int semiIndex = contentType.indexOf(';');
51 if (semiIndex > 0) {
52 mMimeType = contentType.substring(0, semiIndex);
53 } else {
54 mMimeType = contentType;
55 }
56 }
57
58 /**
59 * Returns true if the text passed in appears to be a data URI.
60 */
61 public static boolean isDataUri(String text)
62 {
63 return text.startsWith(DATA_URI_PREFIX);
64 }
65
66 public String getMimeType() {
67 return mMimeType;
68 }
69
70 public byte[] getData() {
71 return mData;
72 }
73}