1 /* 2 * Copyright (C) 2012 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 17 package com.android.gallery3d.filtershow.filters; 18 19 import android.graphics.Bitmap; 20 import android.text.format.Time; 21 22 import com.android.gallery3d.R; 23 24 public class ImageFilterKMeans extends SimpleImageFilter { 25 private static final String SERIALIZATION_NAME = "KMEANS"; 26 private int mSeed = 0; 27 28 public ImageFilterKMeans() { 29 mName = "KMeans"; 30 31 // set random seed for session 32 Time t = new Time(); 33 t.setToNow(); 34 mSeed = (int) t.toMillis(false); 35 } 36 37 public FilterRepresentation getDefaultRepresentation() { 38 FilterBasicRepresentation representation = (FilterBasicRepresentation) super.getDefaultRepresentation(); 39 representation.setName("KMeans"); 40 representation.setSerializationName(SERIALIZATION_NAME); 41 representation.setFilterClass(ImageFilterKMeans.class); 42 representation.setMaximum(20); 43 representation.setMinimum(2); 44 representation.setValue(4); 45 representation.setDefaultValue(4); 46 representation.setPreviewValue(4); 47 representation.setTextId(R.string.kmeans); 48 representation.setSupportsPartialRendering(true); 49 return representation; 50 } 51 52 native protected void nativeApplyFilter(Bitmap bitmap, int width, int height, 53 Bitmap large_ds_bm, int lwidth, int lheight, Bitmap small_ds_bm, 54 int swidth, int sheight, int p, int seed); 55 56 @Override 57 public Bitmap apply(Bitmap bitmap, float scaleFactor, int quality) { 58 if (getParameters() == null) { 59 return bitmap; 60 } 61 int w = bitmap.getWidth(); 62 int h = bitmap.getHeight(); 63 64 Bitmap large_bm_ds = bitmap; 65 Bitmap small_bm_ds = bitmap; 66 67 // find width/height for larger downsampled bitmap 68 int lw = w; 69 int lh = h; 70 while (lw > 256 && lh > 256) { 71 lw /= 2; 72 lh /= 2; 73 } 74 if (lw != w) { 75 large_bm_ds = Bitmap.createScaledBitmap(bitmap, lw, lh, true); 76 } 77 78 // find width/height for smaller downsampled bitmap 79 int sw = lw; 80 int sh = lh; 81 while (sw > 64 && sh > 64) { 82 sw /= 2; 83 sh /= 2; 84 } 85 if (sw != lw) { 86 small_bm_ds = Bitmap.createScaledBitmap(large_bm_ds, sw, sh, true); 87 } 88 89 if (getParameters() != null) { 90 int p = Math.max(getParameters().getValue(), getParameters().getMinimum()) % (getParameters().getMaximum() + 1); 91 nativeApplyFilter(bitmap, w, h, large_bm_ds, lw, lh, small_bm_ds, sw, sh, p, mSeed); 92 } 93 return bitmap; 94 } 95 } 96