android imagepicker now working. Need to generalize the layout stuff and make it lighter still

This commit is contained in:
Andrew Stephan
2014-02-28 17:30:13 -05:00
parent f641587ca4
commit e00327dae7
5 changed files with 154 additions and 106 deletions

View File

@@ -54,21 +54,22 @@ window.imagePicker.getPictures(
### Options
```javascript
options = {
maximumImagesCount: int,
// max images to be selected, defaults to 15. If this is set to 1, upon
// selection of a single image, the plugin will return it.
width: int,
// width to resize image to (if one of height/width is 0, will resize
// to fit the other while keeping aspect ratio, if both height and width
// are 0, the full size image will be returned)
height: int,
// height to resize image to
quality: int (0-100)
// quality of resized image, defaults to 100
};
```
options = {
// max images to be selected, defaults to 15. If this is set to 1, upon
// selection of a single image, the plugin will return it.
maximumImagesCount: int,
// max width and height to allow the images to be. Will keep aspect
// ratio no matter what. So if both are 800, the returned image
// will be at most 800 pixels wide and 800 pixels tall. If the width is
// 800 and height 0 the image will be 800 pixels wide if the source
// is at least that wide.
width: int,
height: int,
// quality of resized image, defaults to 100
quality: int (0-100)
};
## License

View File

@@ -3,31 +3,21 @@
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:orientation="vertical" > <!-- android:background="@drawable/image_bg" -->
<TextView
android:gravity="center"
android:id="@+id/label_images_left"
android:layout_height="wrap_content"
android:layout_weight="0"
android:layout_width="fill_parent"
android:paddingBottom="2dip"
android:paddingTop="2dip"
android:text=""
android:textSize="18sp"
android:textStyle="bold"
android:visibility="gone" />
<GridView
android:fadingEdgeLength="10dip"
android:requiresFadingEdge="vertical"
android:id="@+id/gridview"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:columnWidth="0dip"
android:fadingEdgeLength="10dip"
android:fastScrollEnabled="true"
android:gravity="center"
android:horizontalSpacing="8dip"
android:id="@+id/gridview"
android:layout_height="fill_parent"
android:layout_weight="1"
android:layout_width="fill_parent"
android:numColumns="auto_fit"
android:numColumns="3"
android:requiresFadingEdge="vertical"
android:scrollingCache="true"
android:stretchMode="columnWidth"
android:verticalSpacing="8dip" />
</LinearLayout>

View File

@@ -118,7 +118,7 @@ public class ImageFetcher {
if (bitmapDownloaderTask != null) {
Integer bitmapPosition = bitmapDownloaderTask.position;
if ((bitmapPosition == null) || (!bitmapPosition.equals(position))) {
Log.d("DAVID", "Canceling...");
// Log.d("DAVID", "Canceling...");
MediaStore.Images.Thumbnails.cancelThumbnailRequest(imageView.getContext().getContentResolver(),
origId, 12345);
bitmapDownloaderTask.cancel(true);
@@ -180,7 +180,7 @@ public class ImageFetcher {
return null;
}
Bitmap thumb = MediaStore.Images.Thumbnails.getThumbnail(mContext.getContentResolver(), position, 12345,
MediaStore.Images.Thumbnails.MICRO_KIND, null);
MediaStore.Images.Thumbnails.MINI_KIND, null);
if (isCancelled()) {
return null;
}
@@ -197,7 +197,7 @@ public class ImageFetcher {
}
private void setInvisible() {
Log.d("COLLAGE", "Setting something invisible...");
// Log.d("COLLAGE", "Setting something invisible...");
if (imageViewReference != null) {
final ImageView imageView = imageViewReference.get();
BitmapFetcherTask bitmapDownloaderTask = getBitmapDownloaderTask(imageView);
@@ -324,7 +324,7 @@ public class ImageFetcher {
synchronized (sHardBitmapCache) {
final Bitmap bitmap = sHardBitmapCache.get(position);
if (bitmap != null) {
Log.d("CACHE ****** ", "Hard hit!");
// Log.d("CACHE ****** ", "Hard hit!");
// Bitmap found in hard cache
// Move element to first position, so that it is removed last
return bitmap;
@@ -337,7 +337,7 @@ public class ImageFetcher {
final Bitmap bitmap = bitmapReference.get();
if (bitmap != null) {
// Bitmap found in soft cache
Log.d("CACHE ****** ", "Soft hit!");
// Log.d("CACHE ****** ", "Soft hit!");
return bitmap;
} else {
// Soft reference has been Garbage Collected

View File

@@ -1,3 +1,33 @@
/*
* Copyright (c) 2012, David Erosa
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDIN G NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE
*
* Code modified by Andrew Stephan for Sync OnSet
*
*/
package com.synconset;
import java.util.ArrayList;
@@ -59,9 +89,7 @@ public class MultiImageChooserActivity extends Activity implements OnItemClickLi
private SparseBooleanArray checkStatus = new SparseBooleanArray();
private TextView freeLabel = null;
private int maxImages;
private boolean unlimitedImages = false;
private GridView gridView;
@@ -78,28 +106,17 @@ public class MultiImageChooserActivity extends Activity implements OnItemClickLi
maxImages = getIntent().getIntExtra(MAX_IMAGES_KEY, NOLIMIT);
unlimitedImages = maxImages == NOLIMIT;
if (!unlimitedImages) {
freeLabel = (TextView) findViewById(R.id.label_images_left);
freeLabel.setVisibility(View.VISIBLE);
updateLabel();
}
colWidth = getIntent().getIntExtra(COL_WIDTH_KEY, DEFAULT_COLUMN_WIDTH);
Display display = getWindowManager().getDefaultDisplay();
@SuppressWarnings("deprecation")
int width = display.getWidth();
int testColWidth = width / 3;
if (testColWidth > colWidth) {
colWidth = width / 4;
}
colWidth = width / 4;
// int bgColor = getIntent().getIntExtra("BG_COLOR", Color.BLACK);
gridView = (GridView) findViewById(R.id.gridview);
gridView.setColumnWidth(colWidth);
//gridView.setColumnWidth(colWidth);
gridView.setOnItemClickListener(this);
gridView.setOnScrollListener(new OnScrollListener() {
@@ -109,7 +126,7 @@ public class MultiImageChooserActivity extends Activity implements OnItemClickLi
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
if (scrollState == SCROLL_STATE_IDLE) {
Log.d(TAG, "IDLE - Reload!");
// Log.d(TAG, "IDLE - Reload!");
shouldRequestThumb = true;
ia.notifyDataSetChanged();
}
@@ -122,7 +139,7 @@ public class MultiImageChooserActivity extends Activity implements OnItemClickLi
double speed = 1 / dt * 1000;
lastFirstItem = firstVisibleItem;
timestamp = System.currentTimeMillis();
Log.d(TAG, "Speed: " + speed + " elements/second");
// Log.d(TAG, "Speed: " + speed + " elements/second");
// Limitarlo si vamos a más de una página por segundo...
shouldRequestThumb = speed < visibleItemCount;
@@ -148,7 +165,22 @@ public class MultiImageChooserActivity extends Activity implements OnItemClickLi
private void setupHeader() {
// From Roman Nkk's code
// https://plus.google.com/113735310430199015092/posts/R49wVvcDoEW
// Inflate a "Done/Discard" custom action bar view.
// Inflate a "Done/Discard" custom action bar view
/*
* Copyright 2013 The Android Open Source 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.
*/
LayoutInflater inflater = (LayoutInflater) getActionBar().getThemedContext().getSystemService(
LAYOUT_INFLATER_SERVICE);
final View customActionBarView = inflater.inflate(R.layout.actionbar_custom_view_done_discard, null);
@@ -174,16 +206,15 @@ public class MultiImageChooserActivity extends Activity implements OnItemClickLi
actionBar.setCustomView(customActionBarView, new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT));
}
public class SquareImageView extends ImageView {
public SquareImageView(Context context) {
super(context);
}
private void updateLabel() {
if (freeLabel != null) {
String text = String.format(getString(R.string.free_version_label), maxImages);
freeLabel.setText(text);
if (maxImages == 0) {
freeLabel.setTextColor(Color.RED);
} else {
freeLabel.setTextColor(Color.WHITE);
}
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, widthMeasureSpec);
}
}
@@ -219,10 +250,12 @@ public class MultiImageChooserActivity extends Activity implements OnItemClickLi
public View getView(int pos, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = new ImageView(MultiImageChooserActivity.this);
ImageView temp = new SquareImageView(MultiImageChooserActivity.this);
temp.setScaleType(ImageView.ScaleType.CENTER_CROP);
convertView = (View)temp;
}
ImageView imageView = (ImageView) convertView;
ImageView imageView = (ImageView)convertView;
imageView.setImageBitmap(null);
final int position = pos;
@@ -237,8 +270,10 @@ public class MultiImageChooserActivity extends Activity implements OnItemClickLi
final int id = imagecursor.getInt(image_column_index);
if (isChecked(pos)) {
imageView.setImageAlpha(128);
imageView.setBackgroundColor(selectedColor);
} else {
imageView.setImageAlpha(255);
imageView.setBackgroundColor(Color.TRANSPARENT);
}
if (shouldRequestThumb) {
@@ -291,7 +326,7 @@ public class MultiImageChooserActivity extends Activity implements OnItemClickLi
data.putExtras(res);
this.setResult(RESULT_OK, data);
}
Log.d(TAG, "Returning " + fileNames.size() + " items");
// Log.d(TAG, "Returning " + fileNames.size() + " items");
finish();
}
@@ -303,18 +338,15 @@ public class MultiImageChooserActivity extends Activity implements OnItemClickLi
return;
}
boolean isChecked = !isChecked(position);
// PhotoMix.Log("DAVID", "Posicion " + position + " isChecked: " +
// isChecked);
if (!unlimitedImages && maxImages == 0 && isChecked) {
// PhotoMix.Log("DAVID", "Aquí no debería entrar...");
if (maxImages == 0 && isChecked) {
isChecked = false;
}
if (isChecked) {
// Solo se resta un slot si hemos introducido un
// filename de verdad...
if (fileNames.add(name)) {
maxImages--;
ImageView imageView = (ImageView)view;
imageView.setImageAlpha(128);
view.setBackgroundColor(selectedColor);
}
} else {
@@ -322,14 +354,14 @@ public class MultiImageChooserActivity extends Activity implements OnItemClickLi
// Solo incrementa los slots libres si hemos
// "liberado" uno...
maxImages++;
ImageView imageView = (ImageView)view;
imageView.setImageAlpha(255);
view.setBackgroundColor(Color.TRANSPARENT);
}
}
setChecked(position, isChecked);
updateAcceptButton();
updateLabel();
}
private void updateAcceptButton() {

View File

@@ -1,9 +1,5 @@
/**
* An Image Picker Plugin for Cordova/PhoneGap.
*
* The software is open source, MIT Licensed.
* Portions taken from Copyright (C) 2012, webXells GmbH All Rights Reserved.
*
*/
package com.synconset;
@@ -39,7 +35,11 @@ public class ImagePicker extends CordovaPlugin {
this.params = args.getJSONObject(0);
if (action.equals("getPictures")) {
Intent intent = new Intent(cordova.getActivity(), MultiImageChooserActivity.class);
intent.putExtra("MAX_IMAGES", this.params.getInt("maximumImagesCount"));
int max = 20;
if (this.params.has("maximumImagesCount")) {
max = this.params.getInt("maximumImagesCount");
}
intent.putExtra("MAX_IMAGES", max);
if (this.cordova != null) {
this.cordova.startActivityForResult((CordovaPlugin) this, intent, 0);
}
@@ -57,17 +57,22 @@ public class ImagePicker extends CordovaPlugin {
Bitmap bmp = this.getBitmap(file);
int width = bmp.getWidth();
int height = bmp.getHeight();
int desiredWidth = this.params.getInt("width");
int desiredHeight = this.params.getInt("height");
int desiredWidth = 0;
int desiredHeight = 0;
if (this.params.has("width")) {
desiredWidth = this.params.getInt("width");
}
if (this.params.has("height")) {
desiredHeight = this.params.getInt("height");
}
float widthScale = 1.0f;
float heightScale = 1.0f;
float scale = 1.0f;
if (desiredWidth > 0 || desiredHeight > 0) {
if (desiredHeight == 0 && desiredWidth < width) {
widthScale = (float)desiredWidth/width;
heightScale = widthScale;
scale = (float)desiredWidth/width;
} else if (desiredWidth == 0 && desiredHeight < height) {
heightScale = (float)desiredHeight/height;
widthScale = heightScale;
scale = (float)desiredHeight/height;
} else {
if (desiredWidth > 0 && desiredWidth < width) {
widthScale = (float)desiredWidth/width;
@@ -75,10 +80,15 @@ public class ImagePicker extends CordovaPlugin {
if (desiredHeight > 0 && desiredHeight < height) {
heightScale = (float)desiredHeight/height;
}
if (widthScale < heightScale) {
scale = widthScale;
} else {
scale = heightScale;
}
}
}
if (widthScale < 1 || heightScale < 1) {
bmp = this.getResizedBitmap(bmp, widthScale, heightScale);
if (scale < 1) {
bmp = this.getResizedBitmap(bmp, scale);
}
file = this.storeImage(bmp, file.getName());
res.put(Uri.fromFile(file).toString());
@@ -89,38 +99,53 @@ public class ImagePicker extends CordovaPlugin {
} catch (JSONException e) {
this.callbackContext.error("There was an error importing pictures");
}
} else if (resultCode == Activity.RESULT_CANCELED) {
JSONArray res = new JSONArray();
this.callbackContext.success(res);
} else {
this.callbackContext.error("No images selected");
}
}
/*
* The following functions are originally from
* https://github.com/raananw/PhoneGap-Image-Resizer
*
* They have been modified by Andrew Stephan for Sync OnSet
*
* The software is open source, MIT Licensed.
* Copyright (C) 2012, webXells GmbH All Rights Reserved.
*/
private File storeImage(Bitmap bmp, String fileName) throws JSONException, IOException {
int quality = this.params.getInt("quality");
int index = fileName.lastIndexOf('.');
String name = fileName.substring(0, index);
String ext = fileName.substring(index);
File file = File.createTempFile(name, ext);
OutputStream outStream = new FileOutputStream(file);
if (ext.compareToIgnoreCase(".png") == 0) {
bmp.compress(Bitmap.CompressFormat.PNG, quality, outStream);
} else {
bmp.compress(Bitmap.CompressFormat.JPEG, quality, outStream);
}
int quality = 100;
if (this.params.has("quality")) {
quality = this.params.getInt("quality");
}
int index = fileName.lastIndexOf('.');
String name = fileName.substring(0, index);
String ext = fileName.substring(index);
File file = File.createTempFile(name, ext);
OutputStream outStream = new FileOutputStream(file);
if (ext.compareToIgnoreCase(".png") == 0) {
bmp.compress(Bitmap.CompressFormat.PNG, quality, outStream);
} else {
bmp.compress(Bitmap.CompressFormat.JPEG, quality, outStream);
}
outStream.flush();
outStream.close();
return file;
}
private Bitmap getResizedBitmap(Bitmap bm, float widthFactor, float heightFactor) {
private Bitmap getResizedBitmap(Bitmap bm, float factor) {
int width = bm.getWidth();
int height = bm.getHeight();
// create a matrix for the manipulation
Matrix matrix = new Matrix();
// resize the bit map
matrix.postScale(widthFactor, heightFactor);
matrix.postScale(factor, factor);
// recreate the new Bitmap
Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height,
matrix, false);
Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);
return resizedBitmap;
}