user select image and detect colour - android

package com.example.hello;
//import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
/**
* This activity displays the gallery image picker.
* It displays the image that was picked.
*
* #author ITCuties
*
*/
public class GalleryActivity extends Activity implements OnClickListener {
// Image loading result to pass to startActivityForResult method.
private static int LOAD_IMAGE_RESULTS = 1;
// GUI components
private Button button; // The button
private ImageView image;// ImageView
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gallery);
// Find references to the GUI objects
button = (Button)findViewById(R.id.button);
image = (ImageView)findViewById(R.id.image);
// Set button's onClick listener object.
button.setOnClickListener(this);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Here we need to check if the activity that was triggers was the Image Gallery.
// If it is the requestCode will match the LOAD_IMAGE_RESULTS value.
// If the resultCode is RESULT_OK and there is some data we know that an image was picked.
if (requestCode == LOAD_IMAGE_RESULTS && resultCode == RESULT_OK && data != null) {
// Let's read picked image data - its URI
Uri pickedImage = data.getData();
// Let's read picked image path using content resolver
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(pickedImage, filePath, null, null, null);
cursor.moveToFirst();
String imagePath = cursor.getString(cursor.getColumnIndex(filePath[0]));
// Now we need to set the GUI ImageView data with data read from the picked file.
image.setImageBitmap(BitmapFactory.decodeFile(imagePath));
// At the end remember to close the cursor or you will end with the RuntimeException!
cursor.close();
}
}
#Override
public void onClick(View v) {
// Create the Intent for Image Gallery.
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// Start new activity with the LOAD_IMAGE_RESULTS to handle back the results when image is picked from the Image Gallery.
startActivityForResult(i, LOAD_IMAGE_RESULTS);
}
}
this code select image from gallery ..
package com.example.hello;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageView;
import android.widget.TextView;
public class ColourPickerActivity extends Activity {
TextView touchedXY, invertedXY, imgSize, colorRGB;
ImageView imgSource1, imgSource2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_colourpicker);
// touchedXY = (TextView)findViewById(R.id.xy);
// invertedXY = (TextView)findViewById(R.id.invertedxy);
// imgSize = (TextView)findViewById(R.id.size);
colorRGB = (TextView)findViewById(R.id.colorrgb);
// imgSource1 = (ImageView)findViewById(R.id.source1);
imgSource2 = (ImageView)findViewById(R.id.source2);
//imgSource1.setOnTouchListener(imgSourceOnTouchListener);
imgSource2.setOnTouchListener(imgSourceOnTouchListener);
}
OnTouchListener imgSourceOnTouchListener
= new OnTouchListener(){
#Override
public boolean onTouch(View view, MotionEvent event) {
float eventX = event.getX();
float eventY = event.getY();
float[] eventXY = new float[] {eventX, eventY};
Matrix invertMatrix = new Matrix();
((ImageView)view).getImageMatrix().invert(invertMatrix);
invertMatrix.mapPoints(eventXY);
int x = Integer.valueOf((int)eventXY[0]);
int y = Integer.valueOf((int)eventXY[1]);
// touchedXY.setText(
// "touched position: "
// + String.valueOf(eventX) + " / "
// + String.valueOf(eventY));
// invertedXY.setText(
// "touched position: "
// + String.valueOf(x) + " / "
// + String.valueOf(y));
Drawable imgDrawable = ((ImageView)view).getDrawable();
Bitmap bitmap = ((BitmapDrawable)imgDrawable).getBitmap();
// imgSize.setText(
// "drawable size: "
// + String.valueOf(bitmap.getWidth()) + " / "
// + String.valueOf(bitmap.getHeight()));
//Limit x, y range within bitmap
// if(x < 0){
// x = 0;
// }else if(x > bitmap.getWidth()-1){
// x = bitmap.getWidth()-1;
// }
//
// if(y < 0){
// y = 0;
// }else if(y > bitmap.getHeight()-1){
// y = bitmap.getHeight()-1;
// }
int touchedRGB = bitmap.getPixel(x, y);
colorRGB.setText("touched color: " + "#" + Integer.toHexString(touchedRGB));
colorRGB.setTextColor(touchedRGB);
return true;
}};
}
this code tell colour of pixel on touch of image which is in drawable folder .. how can i integrate these two activities .. i want to select image from gallery and apply colour detector on this image which is selected from gallery

Firs you'll need to call the second class from the fist one inside onActivityResult, adding the imagePath to the Intent:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == LOAD_IMAGE_RESULTS && resultCode == RESULT_OK && data != null) {
(previous code)
Intent intent = new Intent(this, ColourPickerActivity.class);
intent.putExtra("IMAGE_PATH", imagePath);
startActivity(intent)
}
}
Then in your ColourPickerActivity you'll need to extract that path and load it into your ImageView:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
(previous code)
String imagePath = getIntent().getStringExtra("IMAGE_PATH");
//Load image into the ImageView
imgSource2.setImageBitmap(BitmapFactory.decodeFile(imagePath));
}
Hope that helps, cheers!

Related

Pick color from Image in ImageView [Problem]

I'm making an app in which I pick image using Camera/Gallery Intent and then set it to ImageView. After that onTouch on the image(in ImageView) I get Hex, RGB and HSL values of the color of the touched pixel of the image.
This works well for the image imported the first time but when I import image second time and touch on that new image it gives me the color of the previous image.
Here is my code:
package com.blogspot.atifsoftwares.colorslab;
import android.Manifest;
import android.content.ClipboardManager;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.text.NumberFormat;
public class PickFromImageActivity extends AppCompatActivity {
ImageView mImageView;
TextView mResultTv;
ImageButton mCopyBtn, mShareBtn;
Bitmap bitmap;
View view;
Uri image_uri;
private static final int IMAGE_PICK_GALLERY_CODE = 1000;
private static final int IMAGE_PICK_CAMERA_CODE = 1001;
private static final int PERMISSION_READ_STORAGE_CODE = 1002;
private static final int PERMISSION_WRITE_STORAGE_CODE = 1003;
private static final int PERMISSION_CAMERA_CODE = 1004;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pick_from_image);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setTitle("Color Picker");
actionBar.setSubtitle("Pick color from Image");
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
mImageView =findViewById(R.id.imageIv);
mResultTv = findViewById(R.id.restultTv);
mCopyBtn = findViewById(R.id.copyBtn);
mShareBtn = findViewById(R.id.shareBtn);
view = findViewById(R.id.colorView);
mImageView.setDrawingCacheEnabled(true);
mImageView.buildDrawingCache(true);
mImageView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN || event.getAction() == MotionEvent.ACTION_MOVE){
bitmap = mImageView.getDrawingCache();
int pixel = bitmap.getPixel((int)event.getX(), (int) event.getY());
int r = Color.red(pixel);
int g = Color.green(pixel);
int b = Color.blue(pixel);
int color = Color.TRANSPARENT;
Drawable background = view.getBackground();
if (background instanceof ColorDrawable)
color = ((ColorDrawable) background).getColor();
view.setBackgroundColor(Color.rgb(r,g,b));
mResultTv.setText("HEX: "+ String.format("#%06X", 0xFFFFFF & color)
+"\nRGB: "+ r +", "+ g +", "+ b
+"\nHSL: "+ rgbToHsl(r,g,b));
}
return true;
}
});
mCopyBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String data = mResultTv.getText().toString();
ClipboardManager cb = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
cb.setText(data);
Toast.makeText(PickFromImageActivity.this, "Copied...!", Toast.LENGTH_SHORT).show();
}
});
mShareBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String data = mResultTv.getText().toString();
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Subject Here");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, data);
startActivity(Intent.createChooser(sharingIntent, "Share via"));
}
});
}
private String rgbToHsl(int r, int g, int b) {
final float rf = r / 255f;
final float gf = g / 255f;
final float bf = b / 255f;
final float max = Math.max(rf, Math.max(gf, bf));
final float min = Math.min(rf, Math.min(gf, bf));
final float deltaMaxMin = max - min;
float h, s;
float l = (max + min) / 2f;
if (max == min) {
// Monochromatic
h = s = 0f;
} else {
if (max == rf) {
h = ((gf - bf) / deltaMaxMin) % 6f;
} else if (max == gf) {
h = ((bf - rf) / deltaMaxMin) + 2f;
} else {
h = ((rf - gf) / deltaMaxMin) + 4f;
}
s = deltaMaxMin / (1f - Math.abs(2f * l - 1f));
}
h = (h * 60f) % 360f;
s = s*100;
l = l*100;
NumberFormat formH = NumberFormat.getNumberInstance();
formH.setMinimumFractionDigits(0);
formH.setMaximumFractionDigits(0);
String formattedH = formH.format(h);
NumberFormat formS = NumberFormat.getNumberInstance();
formS.setMinimumFractionDigits(0);
formS.setMaximumFractionDigits(0);
String formattedS = formS.format(s);
NumberFormat formL = NumberFormat.getNumberInstance();
formL.setMinimumFractionDigits(0);
formL.setMaximumFractionDigits(0);
String formattedL = formL.format(l);
return ""+ formattedH +", "+ formattedS +"%, "+ formattedL +"%";
}
public void pickCamera(){
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "New Picture");
values.put(MediaStore.Images.Media.DESCRIPTION, "From Camera");
image_uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, image_uri);
startActivityForResult(cameraIntent, IMAGE_PICK_CAMERA_CODE);
}
public void pickGallery(){
//intent to pick image
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, IMAGE_PICK_GALLERY_CODE);
}
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu, menu);
menu.findItem(R.id.action_search).setVisible(false);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_about) {
startActivity(new Intent(this, AboutActivity.class));
return true;
} else if (id == R.id.action_rate) {
try {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=com.blogspot.atifsoftwares.colorslab")));
} catch (android.content.ActivityNotFoundException anfe) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=com.blogspot.atifsoftwares.colorslab")));
}
return true;
} else if (id == R.id.action_more) {
try {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/dev?id=6868537621115215530")));
} catch (android.content.ActivityNotFoundException anfe) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/dev?id=6868537621115215530")));
}
return true;
}
else if (id == R.id.action_share) {
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
String shareBody = "\"Colors Lab\" contains important tools such as Popular Colors, Pick Color from color platte, Pick Color from Image, Convert Color from and to Hex, RGB, HSL.:\n https://play.google.com/store/apps/details?id=com.blogspot.atifsoftwares.colorslab";
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Subject Here");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
startActivity(Intent.createChooser(sharingIntent, "Share via"));
}
else if (id == R.id.action_camera) {
//check runtime permission
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
if (checkSelfPermission(Manifest.permission.CAMERA)
== PackageManager.PERMISSION_DENIED ||
checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_DENIED){
//permission not granted, request it.
String[] permissions = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
//show popup for runtime permission
requestPermissions(permissions, PERMISSION_WRITE_STORAGE_CODE);
}
else {
//permission already granted
pickCamera();
}
}
else {
//system os is less then marshmallow
pickCamera();
}
}
else if (id == R.id.action_gallery) {
//check runtime permission
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_DENIED){
//permission not granted, request it.
String[] permissions = {Manifest.permission.READ_EXTERNAL_STORAGE};
//show popup for runtime permission
requestPermissions(permissions, PERMISSION_READ_STORAGE_CODE);
}
else {
//permission already granted
pickGallery();
}
}
else {
//system os is less then marshmallow
pickGallery();
}
}
return super.onOptionsItemSelected(item);
}
//handle result of runtime permission
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode){
case PERMISSION_READ_STORAGE_CODE:{
if (grantResults.length >0 && grantResults[0] ==
PackageManager.PERMISSION_GRANTED){
//permission was granted
pickGallery();
}
else {
//permission was denied
Toast.makeText(this, "Permission denied...!", Toast.LENGTH_SHORT).show();
}
}
case PERMISSION_CAMERA_CODE:{
if (grantResults.length >0 && grantResults[0] ==
PackageManager.PERMISSION_GRANTED){
//permission was granted
pickCamera();
}
else {
//permission was denied
Toast.makeText(this, "Permission denied...!", Toast.LENGTH_SHORT).show();
}
}
}
}
//handle result of picked image
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK){
if (requestCode == IMAGE_PICK_GALLERY_CODE){
//set image to image view
mImageView.setImageURI(data.getData());
}
if (requestCode == IMAGE_PICK_CAMERA_CODE){
//set image to image view
mImageView.setImageURI(image_uri);
}
}
}
}
Screen shot:
before adding image
write this piece of code
ImgView.setImageBitmap(null);
ImgView.destroyDrawingCache();
In order to get color, first you have to get the pixel which is clicked by user
To get a pixel, you must get the bitmap on a canvas and then read the RGB values of that clicked pixel
Below code will help you do so
Bitmap bitmap = ((BitmapDrawable)image.getDrawable()).getBitmap();
int pixel = bitmap.getPixel(x,y); // x and y are coordinates
int redValue = Color.red(pixel);
int blueValue = Color.blue(pixel);
int greenValue = Color.green(pixel);
if(pixel == Color.RED){
// color is red
}
You can use multiple conditions or a logic to create RGB code from above values.
Add before adding the image...
mImageView.setImageBitmap(null);
mImageView.destroyDrawingCache();

App crashing when detecting faces in large size images

I am fetching the image from the phone's gallery and setting it in an imageview and using the mobile vision library of google trying to detect the faces in that image. i have also reduced the image size so now the first large size image will get loaded in the image view properly but if you try to load another large size image the app would crash. Also while detecting the faces of large size image the app is crashing in those images the app is getting crashed.
Logcat:
MainActivity.java
package com.imagegallery.app.imagegallery;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.util.SparseArray;
import android.view.Display;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import com.google.android.gms.vision.Frame;
import com.google.android.gms.vision.face.Face;
import com.google.android.gms.vision.face.FaceDetector;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private int PICK_IMAGE_REQUEST=1;
Button btnLoad, btnDetFace;
int count=0;
Context cntx;
String open_time,close_time;
DatabaseHandler db = new DatabaseHandler(this);
Bitmap bitmap;
ImageView imageView;
String img_name, realPath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cntx=this;
btnLoad=(Button) findViewById(R.id.btn_open);
btnLoad.setOnClickListener(this);
btnDetFace=(Button) findViewById(R.id.detection);
btnDetFace.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
// Return true to display menu
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
Intent dbmanager = new Intent(this,AndroidDatabaseManager.class);
startActivity(dbmanager);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_open:
Intent intent = new Intent();
intent.setType("image/* video/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, PICK_IMAGE_REQUEST);
break;
case R.id.detection:
if(bitmap == null){
Toast.makeText(MainActivity.this, "bitmap == null",
Toast.LENGTH_LONG).show();
}
else{
detectFace();
Toast.makeText(MainActivity.this,"Done",
Toast.LENGTH_LONG).show();
}
break;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri uri = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
imageView = (ImageView) findViewById(R.id.imageView);
//compressImage(uri);
// imageView.setImageBitmap(bitmap);
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
// SDK < API11
if (Build.VERSION.SDK_INT < 11)
realPath = RealPathUtil.getRealPathFromURI_BelowAPI11(this, data.getData());
// SDK >= 11 && SDK < 19
else if (Build.VERSION.SDK_INT < 19)
realPath = RealPathUtil.getRealPathFromURI_API11to18(this, data.getData());
// SDK > 19 (Android 4.4)
else
realPath = RealPathUtil.getRealPathFromURI_API19(this, data.getData());
imageView.setImageBitmap(ImageResizer
.decodeSampledBitmapFromFile(realPath, width, height));
img_name=realPath.substring(realPath.lastIndexOf("/")+1);
count = ++count;
if (count == 1) {
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT+5:30"));
Date currentLocalTime = cal.getTime();
DateFormat date = new SimpleDateFormat("hh:mm:ss");
date.setTimeZone(TimeZone.getTimeZone("GMT+5:30"));
String localTime = date.format(currentLocalTime);
open_time = localTime;
}
else if (count > 1) {
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT+5:30"));
Date currentLocalTime = cal.getTime();
DateFormat date = new SimpleDateFormat("hh:mm:ss");
date.setTimeZone(TimeZone.getTimeZone("GMT+5:30"));
String localTime = date.format(currentLocalTime);
close_time = localTime;
Log.d("Insert: ", "Inserting ..");
db.addTime(new Time(img_name,open_time, close_time));
open_time = localTime;
Log.d("Reading: ", "Reading all contacts..");
List<Time> time = db.getAllData();
for (Time t : time) {
String log = "Start time: " + t.getStartTime() + " ,End Time: " + t.getEndTime();
// Writing Time to log
Log.d("Time: ", log);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void detectFace(){
//Create a Paint object for drawing with
Paint myRectPaint = new Paint();
myRectPaint.setStrokeWidth(5);
myRectPaint.setColor(Color.RED);
myRectPaint.setStyle(Paint.Style.STROKE);
//Create a Canvas object for drawing on
Bitmap tempBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.RGB_565);
Canvas tempCanvas = new Canvas(tempBitmap);
tempCanvas.drawBitmap(bitmap, 0, 0, null);
//Detect the Faces
FaceDetector faceDetector = new FaceDetector.Builder(getApplicationContext()).build();
//!!!
//Cannot resolve method setTrackingEnabled(boolean)
//skip for now
//faceDetector.setTrackingEnabled(false);
Frame frame = new Frame.Builder().setBitmap(bitmap).build();
SparseArray<Face> faces = faceDetector.detect(frame);
//Draw Rectangles on the Faces
for(int i=0; i<faces.size(); i++) {
Face thisFace = faces.valueAt(i);
float x1 = thisFace.getPosition().x;
float y1 = thisFace.getPosition().y;
float x2 = x1 + thisFace.getWidth();
float y2 = y1 + thisFace.getHeight();
tempCanvas.drawRoundRect(new RectF(x1, y1, x2, y2), 2, 2, myRectPaint);
}
imageView.setImageDrawable(new BitmapDrawable(getResources(),tempBitmap));
}
}
set following code in manifest file application tag
android:largeHeap="true"
Better to compress the image size using bitmap Compress function
tempBitmap.compress(Bitmap.CompressFormat.JPEG, 70, FileName);
you can adjust compress value as you like.
http://developer.android.com/training/displaying-bitmaps/index.html
You have to use Recycleimageview which is provide by Android for this situation. You can compress bitmap at display time.. Please review given link implment it your issue will resolve.
And android:largeHeap="true" support from Android 3.0 to latest version it does't support to 2.3 version and This is not solution. You have use recycleimage if you want fix issue properly.

navigating to a specific page with the mupdf android library

How would I go about navigating to a specific page with the muPDF library? Or is there a way to make the library not remember which page I was last on in that pdf?
Uri uri = Uri.parse(path);
Intent intent = new Intent(MainActivity.getContext(), MuPDFActivity.class)
intent.setAction(Intent.ACTION_VIEW);
intent.setData(uri);
c.startActivity(intent);
//c is context
This is how i'm currently opening pdfs.
You can add page index in Bundle into your intent, load that index in MuPDFActivity thereafter and call mDocView.setDisplayedViewIndex(your_index_from_bundle); That should do the job.
Something like that:
Uri uri = Uri.parse(path);
Intent intent = new Intent(MainActivity.getContext(), MuPDFActivity.class)
intent.setAction(Intent.ACTION_VIEW);
intent.setData(uri);
Bundle extras = intent.getExtras();
extras.putInt("key_page_index", 10);
c.startActivity(intent);
Then edit onCreate in MuPDFActivity, add this code at the end of the onCreate:
Intent intent = getIntent();
if(intent!=null){
Bundle extras = intent.getExtras();
if(extras!=null){
int index = extras.getInt("key_page_index");
mDocView.setDisplayedViewIndex(index);
}
}
package com.artifex.mupdf;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.util.Log;
public class MuPDFPageView extends PageView {
private final MuPDFCore mCore;
public MuPDFPageView(Context c, MuPDFCore core, Point parentSize) {
super(c, parentSize);
mCore = core;
}
public String hitLinkPage(float x, float y) {
// Since link highlighting was implemented, the super class
// PageView has had sufficient information to be able to
// perform this method directly. Making that change would
// make MuPDFCore.hitLinkPage superfluous.
float scale = mSourceScale * getWidth() / mSize.x ;
float docRelX = (x - getLeft()) / scale;
float docRelY = (y - getTop()) / scale;
Log.d("Page Number", "hitLinkPage with page = " + mCore.hitLinkPage(mPageNumber, docRelX, docRelY));
return mCore.hitLinkPage(mPageNumber, docRelX, docRelY);
}
#Override
protected void drawPage(Bitmap bm, int sizeX, int sizeY, int patchX,
int patchY, int patchWidth, int patchHeight) {
mCore.drawPage(mPageNumber, bm, sizeX, sizeY, patchX, patchY,
patchWidth, patchHeight);
}
#Override
protected LinkInfo[] getLinkInfo() {
return mCore.getPageLinks(mPageNumber);
}
}

My barcode app force closes whenever it runs

I got my app to read an app and then tell me what the code says, but now I'm trying to have it encode the string back into a barcode and display it as an image on the screen. However, it always force closes the app before it starts. Here is my code, please help:
import java.util.EnumMap;
import java.util.Map;
import android.os.Bundle;
import android.app.ActionBar.LayoutParams;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.view.Gravity;
import android.view.Menu;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
public class Main extends Activity {
IntentIntegrator integrator = new IntentIntegrator(this);
private static final int WHITE = 0xFFFFFFFF;
private static final int BLACK = 0xFF000000;
LinearLayout myLayout = (LinearLayout)findViewById(R.id.myLayout);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//LinearLayout myLayout = (LinearLayout)findViewById(R.id.myLayout);
Button btn =(Button)findViewById(R.id.button1);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
integrator.initiateScan();
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanResult != null) {
Toast.makeText(Main.this,
"works",
Toast.LENGTH_SHORT).show();
String contents = intent.getStringExtra("SCAN_RESULT");
String format = intent.getStringExtra("SCAN_RESULT_FORMAT");
Toast.makeText(Main.this,
contents,
Toast.LENGTH_SHORT).show();
Bitmap bitmap = null;
ImageView iv = new ImageView(this);
try {
bitmap = encodeAsBitmap(contents, BarcodeFormat.CODE_128, 600, 300);
iv.setImageBitmap(bitmap);
} catch (WriterException e) {
e.printStackTrace();
}
myLayout.addView(iv);
TextView tv = new TextView(this);
tv.setGravity(Gravity.CENTER_HORIZONTAL);
tv.setText(contents);
myLayout.addView(tv);
}
}
Bitmap encodeAsBitmap(String contents, BarcodeFormat format, int img_width, int img_height) throws WriterException {
String contentsToEncode = contents;
if (contentsToEncode == null) {
return null;
}
Map<EncodeHintType, Object> hints = null;
hints = new EnumMap<EncodeHintType, Object>(EncodeHintType.class);
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
MultiFormatWriter writer = new MultiFormatWriter();
BitMatrix result;
try {
result = writer.encode(contentsToEncode, format, img_width, img_height, hints);
} catch (IllegalArgumentException iae) {
// Unsupported format
return null;
}
int width = result.getWidth();
int height = result.getHeight();
int[] pixels = new int[width * height];
for (int y = 0; y < height; y++) {
int offset = y * width;
for (int x = 0; x < width; x++) {
pixels[offset + x] = result.get(x, y) ? BLACK : WHITE;
}
}
Bitmap bitmap = Bitmap.createBitmap(width, height,
Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
return bitmap;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
IntentResult and IntentIntegrator are both from ZXing.
Log Cat:
03-15 13:05:04.303: E/AndroidRuntime(4363): FATAL EXCEPTION: main
In your toast, instead of Main.this you should try getApplicationContext(). Also recall that an Activity is a type of Context.
Try to move this:
LinearLayout myLayout = (LinearLayout)findViewById(R.id.myLayout);
under:
setContentView(R.layout.main);

How to select a file from Android Emulator?

These are the codes which appeared to have no error but activity stops when I clicked on the Select File button. I wish to upload a file to Amazon S3 but I have to choose a file before uploading. The File I wish to upload is from "Downloads" of the emulator.
Anyone know what's wrong?
package sit.nyp.edu.sg.filepicker;
import java.io.File;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class FilePicker2Activity extends Activity {
/** Called when the activity is first created. */
TextView textFile, textFileName, textFolder;
TextView textFileName_WithoutExt, textFileName_Ext;
private static final int PICKFILE_RESULT_CODE = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button buttonPick = (Button)findViewById(R.id.buttonpick);
textFile = (TextView)findViewById(R.id.textfile);
textFolder = (TextView)findViewById(R.id.textfolder);
textFileName = (TextView)findViewById(R.id.textfilename);
textFileName_WithoutExt = (TextView)findViewById(R.id.textfilename_withoutext);
textFileName_Ext = (TextView)findViewById(R.id.textfilename_ext);
buttonPick.setOnClickListener(new Button.OnClickListener(){
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setAction(Intent.ACTION_PICK);
intent.setType("file/*");
startActivityForResult(intent,PICKFILE_RESULT_CODE);
}});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
switch(requestCode){
case PICKFILE_RESULT_CODE:
if(resultCode==RESULT_OK){
String FilePath = data.getData().getPath();
String FileName = data.getData().getLastPathSegment();
int lastPos = FilePath.length() - FileName.length();
String Folder = FilePath.substring(0, lastPos);
textFile.setText("Full Path: \n" + FilePath + "\n");
textFolder.setText("Folder: \n" + Folder + "\n");
textFileName.setText("File Name: \n" + FileName + "\n");
filename thisFile = new filename(FileName);
textFileName_WithoutExt.setText("Filename without Ext: " + thisFile.getFilename_Without_Ext());
textFileName_Ext.setText("Ext: " + thisFile.getExt());
}
break;
}
}
private class filename{
String filename_Without_Ext = "";
String ext = "";
filename(String file){
int dotposition= file.lastIndexOf(".");
filename_Without_Ext = file.substring(0,dotposition);
ext = file.substring(dotposition + 1, file.length());
}
String getFilename_Without_Ext(){
return filename_Without_Ext;
}
String getExt(){
return ext;
}
}
}
My guess is that, you dont have any file browser apps which can handle get content intent on the emulator, though if you post the log , can come to conclusion clearly.

Categories

Resources