summaryrefslogtreecommitdiffstats
path: root/core/java/com/android/internal/util/cm/ImageUtils.java
blob: f2a5e0cd6b0a689c47fd70be0adc0b60ca23390c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
/*
 * Copyright (C) 2013-2014 The CyanogenMod Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.internal.util.cm;

import android.app.WallpaperManager;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.ThemeUtils;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.net.Uri;
import android.provider.ThemesContract;
import android.provider.ThemesContract.ThemesColumns;
import android.text.TextUtils;
import android.util.Log;
import android.view.WindowManager;
import android.webkit.URLUtil;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;

import libcore.io.IoUtils;

public class ImageUtils {
    private static final String TAG = ImageUtils.class.getSimpleName();

    private static final String ASSET_URI_PREFIX = "file:///android_asset/";
    private static final int DEFAULT_IMG_QUALITY = 100;

    /**
     * Gets the Width and Height of the image
     *
     * @param inputStream The input stream of the image
     *
     * @return A point structure that holds the Width and Height (x and y)/*"
     */
    public static Point getImageDimension(InputStream inputStream) {
        if (inputStream == null) {
            throw new IllegalArgumentException("'inputStream' cannot be null!");
        }
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(inputStream, null, options);
        Point point = new Point(options.outWidth,options.outHeight);
        return point;
    }

    /**
     * Crops the input image and returns a new InputStream of the cropped area
     *
     * @param inputStream The input stream of the image
     * @param imageWidth Width of the input image
     * @param imageHeight Height of the input image
     * @param inputStream Desired Width
     * @param inputStream Desired Width
     *
     * @return a new InputStream of the cropped area/*"
     */
    public static InputStream cropImage(InputStream inputStream, int imageWidth, int imageHeight,
            int outWidth, int outHeight) throws IllegalArgumentException {
        if (inputStream == null){
            throw new IllegalArgumentException("inputStream cannot be null");
        }

        if (imageWidth <= 0 || imageHeight <= 0) {
            throw new IllegalArgumentException(
                    String.format("imageWidth and imageHeight must be > 0: imageWidth=%d" +
                            " imageHeight=%d", imageWidth, imageHeight));
        }

        if (outWidth <= 0 || outHeight <= 0) {
            throw new IllegalArgumentException(
                    String.format("outWidth and outHeight must be > 0: outWidth=%d" +
                            " outHeight=%d", imageWidth, outHeight));
        }

        int scaleDownSampleSize = Math.min(imageWidth / outWidth, imageHeight / outHeight);
        if (scaleDownSampleSize > 0) {
            imageWidth /= scaleDownSampleSize;
            imageHeight /= scaleDownSampleSize;
        } else {
            float ratio = (float) outWidth / outHeight;
            if (imageWidth < imageHeight * ratio) {
                outWidth = imageWidth;
                outHeight = (int) (outWidth / ratio);
            } else {
                outHeight = imageHeight;
                outWidth = (int) (outHeight * ratio);
            }
        }
        int left = (imageWidth - outWidth) / 2;
        int top = (imageHeight - outHeight) / 2;
        InputStream compressed = null;
        try {
            BitmapFactory.Options options = new BitmapFactory.Options();
            if (scaleDownSampleSize > 1) {
                options.inSampleSize = scaleDownSampleSize;
            }
            Bitmap bitmap = BitmapFactory.decodeStream(inputStream, null, options);
            if (bitmap == null) {
                return null;
            }
            Bitmap cropped = Bitmap.createBitmap(bitmap, left, top, outWidth, outHeight);
            ByteArrayOutputStream tmpOut = new ByteArrayOutputStream(2048);
            if (cropped.compress(Bitmap.CompressFormat.PNG, DEFAULT_IMG_QUALITY, tmpOut)) {
                byte[] outByteArray = tmpOut.toByteArray();
                compressed = new ByteArrayInputStream(outByteArray);
            }
        } catch (Exception e) {
            Log.e(TAG, "Exception " + e);
        }
        return compressed;
    }

    /**
     * Crops the lock screen image and returns a new InputStream of the cropped area
     *
     * @param pkgName Name of the theme package
     * @param context The context
     *
     * @return a new InputStream of the cropped image/*"
     */
    public static InputStream getCroppedKeyguardStream(String pkgName, Context context)
            throws IllegalArgumentException {
        if (TextUtils.isEmpty(pkgName)) {
            throw new IllegalArgumentException("'pkgName' cannot be null or empty!");
        }
        if (context == null) {
            throw new IllegalArgumentException("'context' cannot be null!");
        }

        InputStream cropped = null;
        InputStream stream = null;
        try {
            stream = getOriginalKeyguardStream(pkgName, context);
            if (stream == null) {
                return null;
            }
            Point point = getImageDimension(stream);
            IoUtils.closeQuietly(stream);
            if (point == null || point.x == 0 || point.y == 0) {
                return null;
            }
            WallpaperManager wm = WallpaperManager.getInstance(context);
            WindowManager service = (WindowManager) context.getSystemService(
                    Context.WINDOW_SERVICE);
            Point size = new Point();
            service.getDefaultDisplay().getSize(size);
            int outWidth = size.x;
            int outHeight = size.y;
            stream = getOriginalKeyguardStream(pkgName, context);
            if (stream == null) {
                return null;
            }
            cropped = cropImage(stream, point.x, point.y, outWidth, outHeight);
        } catch (Exception e) {
            Log.e(TAG, "Exception " + e);
        } finally {
            IoUtils.closeQuietly(stream);
        }
        return cropped;
    }

    /**
     * Crops the wallpaper image and returns a new InputStream of the cropped area
     *
     * @param pkgName Name of the theme package
     * @param context The context
     *
     * @return a new InputStream of the cropped image/*"
     */
    public static InputStream getCroppedWallpaperStream(String pkgName, Context context) {
        if (TextUtils.isEmpty(pkgName)) {
            throw new IllegalArgumentException("'pkgName' cannot be null or empty!");
        }
        if (context == null) {
            throw new IllegalArgumentException("'context' cannot be null!");
        }

        InputStream cropped = null;
        InputStream stream = null;
        try {
            stream = getOriginalWallpaperStream(pkgName, context);
            if (stream == null) {
                return null;
            }
            Point point = getImageDimension(stream);
            IoUtils.closeQuietly(stream);
            if (point == null || point.x == 0 || point.y == 0) {
                return null;
            }
            WallpaperManager wm = WallpaperManager.getInstance(context);
            int outWidth = wm.getDesiredMinimumWidth();
            int outHeight = wm.getDesiredMinimumHeight();
            stream = getOriginalWallpaperStream(pkgName, context);
            if (stream == null) {
                return null;
            }
            cropped = cropImage(stream, point.x, point.y, outWidth, outHeight);
        } catch (Exception e) {
            Log.e(TAG, "Exception " + e);
        } finally {
            IoUtils.closeQuietly(stream);
        }
        return cropped;
    }

    private static InputStream getOriginalKeyguardStream(String pkgName, Context context) {
        if (TextUtils.isEmpty(pkgName) || context == null) {
            return null;
        }

        InputStream inputStream = null;
        try {
            //Get input WP stream from the theme
            Context themeCtx = context.createPackageContext(pkgName,
                    Context.CONTEXT_IGNORE_SECURITY);
            AssetManager assetManager = themeCtx.getAssets();
            String wpPath = ThemeUtils.getLockscreenWallpaperPath(assetManager);
            if (wpPath == null) {
                Log.w(TAG, "Not setting lockscreen wp because wallpaper file was not found.");
            } else {
                inputStream = ThemeUtils.getInputStreamFromAsset(themeCtx,
                        ASSET_URI_PREFIX + wpPath);
            }
        } catch (Exception e) {
            Log.e(TAG, "There was an error setting lockscreen wp for pkg " + pkgName, e);
        }
        return inputStream;
    }

    private static InputStream getOriginalWallpaperStream(String pkgName, Context context) {
        if (TextUtils.isEmpty(pkgName) || context == null) {
            return null;
        }

        InputStream inputStream = null;
        String selection = ThemesContract.ThemesColumns.PKG_NAME + "= ?";
        String[] selectionArgs = {pkgName};
        Cursor c = context.getContentResolver().query(ThemesColumns.CONTENT_URI,
                null, selection,
                selectionArgs, null);
        if (c == null || c.getCount() < 1) {
            if (c != null) c.close();
            return null;
        } else {
            c.moveToFirst();
        }

        try {
            Context themeContext = context.createPackageContext(pkgName,
                    Context.CONTEXT_IGNORE_SECURITY);
            boolean isLegacyTheme = c.getInt(
                    c.getColumnIndex(ThemesColumns.IS_LEGACY_THEME)) == 1;
            if (!isLegacyTheme) {
                String wallpaper = c.getString(
                        c.getColumnIndex(ThemesColumns.WALLPAPER_URI));
                if (wallpaper != null) {
                    if (URLUtil.isAssetUrl(wallpaper)) {
                        inputStream = ThemeUtils.getInputStreamFromAsset(themeContext, wallpaper);
                    } else {
                        inputStream = context.getContentResolver().openInputStream(
                                Uri.parse(wallpaper));
                    }
                } else {
                    // try and get the wallpaper directly from the apk if the URI was null
                    Context themeCtx = context.createPackageContext(pkgName,
                            Context.CONTEXT_IGNORE_SECURITY);
                    AssetManager assetManager = themeCtx.getAssets();
                    String wpPath = ThemeUtils.getWallpaperPath(assetManager);
                    if (wpPath == null) {
                        Log.e(TAG, "Not setting wp because wallpaper file was not found.");
                    } else {
                        inputStream = ThemeUtils.getInputStreamFromAsset(themeCtx,
                                ASSET_URI_PREFIX + wpPath);
                    }
                }
            } else {
                Resources resources = context.getResources();
                PackageInfo pi = context.getPackageManager().getPackageInfo(pkgName, 0);

                if (pi.legacyThemeInfos != null && pi.legacyThemeInfos.length > 0) {
                    inputStream =
                            resources.openRawResource(pi.legacyThemeInfos[0].wallpaperResourceId);
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "getWallpaperStream: " + e);
        } finally {
            c.close();
        }

        return inputStream;
    }
}