My application can't store the image taken with OpenCV Library - android

I am developping an android application for face recognition ,and when i press the button to store the picture , My app stopped !!
Here is my code the the Activity Add Picture :
public class Add_Picture extends FragmentActivity implements CvCameraViewListener2 {
static {
if (!OpenCVLoader.initDebug()) {
// Handle initialization error
Log.e("no","no");
}
else {
Log.e("ok","ok");
}
}
static
{
// If you use opencv 2.4, System.loadLibrary("opencv_java")
System.loadLibrary("opencv_java3");
}
private static final String TAG = "Reconnaissance Faciale";
public static final int VIEW_MODE_LISTFRAMES= 1;
private MenuItem listframes;
public static int viewMode;
private Mat mRgba;
private CameraBridgeViewBase mOpenCvCameraView;
private DBhelper dbhelper;
private Button store;
private Button back;
private EditText text;
private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
#Override
public void onManagerConnected(int status) {
switch (status) {
case LoaderCallbackInterface.SUCCESS:
{
Log.i(TAG, "OpenCV loaded successfully");
mOpenCvCameraView.enableView();
} break;
default:
{
super.onManagerConnected(status);
} break;
}
}
};
public Add_Picture() {
Log.i(TAG, "Instantiated new " + this.getClass());
}
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.i(TAG, "called onCreate");
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(com.example.opencv_java_androidstudio.R.layout.activity_add__picture);
// setContentView(R.layout.activity_add__picture);
//setContentView(R.layout.activity_add__picture);
//mOpenCvCameraView = (CameraBridgeViewBase) findViewById(R.id.camera);
mOpenCvCameraView = (CameraBridgeViewBase) findViewById(com.example.opencv_java_androidstudio.R.id.camera);
mOpenCvCameraView.setCvCameraViewListener(this);
mOpenCvCameraView.setCameraIndex(1);
mOpenCvCameraView.setVisibility(SurfaceView.VISIBLE);
//mOpenCvCameraView.setRotation(90);
//store= (Button) findViewById(R.id.store);
store= (Button) findViewById(com.example.opencv_java_androidstudio.R.id.store);
store.setRotation(90);
Mat test = new Mat(200, 200, CvType.CV_8UC1);
Imgproc.equalizeHist(test, test);
//mOpenCvCameraView.getDisplay();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
listframes = menu.add("Faces list");
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item == listframes){
viewMode = VIEW_MODE_LISTFRAMES;
// Intent intent = new Intent(AjoutframeActivity.this, ListframeActivity.class);
// startActivity(intent);
}
return true;
}
#Override
public void onPause()
{
if (mOpenCvCameraView != null)
mOpenCvCameraView.disableView();
super.onPause();
}
#Override
public void onResume()
{
super.onResume();
OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_3, this, mLoaderCallback);
}
public void onDestroy() {
super.onDestroy();
if (mOpenCvCameraView != null)
mOpenCvCameraView.disableView();
}
public void onCameraViewStarted(int width, int height) {
mRgba = new Mat(height, width, CvType.CV_8UC4);
}
public void onCameraViewStopped() {
mRgba.release();
}
public Mat onCameraFrame(CvCameraViewFrame inputFrame) {
mRgba=inputFrame.rgba();
store.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v1){
storeframesiDB(mRgba);
}
});
return mRgba;
}
public void storeframesiDB(Mat mat){
MatOfKeyPoint points = new MatOfKeyPoint();
FeatureDetector surf = FeatureDetector.create(FeatureDetector.ORB);
DescriptorExtractor extractor = DescriptorExtractor.create(DescriptorExtractor.BRIEF);
surf.detect(mat, points);
Mat descriptors = new Mat();
extractor.compute(mat, points, descriptors);
int rows=descriptors.rows();
String str=Frametraitement.matToJson(descriptors);
dbhelper = new DBhelper(this);
//text= (EditText) findViewById(R.id.storage);
text= (EditText) findViewById(com.example.opencv_java_androidstudio.R.id.storage);
String textstore= text.getText().toString();
Frameclass fr = new Frameclass(textstore,str,rows);
text.setText("");
dbhelper.open();
dbhelper.insertframeDetails(fr);
dbhelper.close();
}
}
My Logcat shows me that : Canno't load info library for OpenCV.
And here is my class for the image's traitement :
public class Frametraitement {
private static final String TAG = "RF";
private DBhelper dbhelper;
public static Mat matRetrieve(String filePath, int rows, int cols, int type){
Log.d(TAG, "matRetrieve - path: " + filePath);
if(isExternalStorageReadable()){
File matFile = new File(filePath);
InputStream in = null;
try {
in = new FileInputStream(matFile);
byte[] data = convertInputStreamToByteArray(in);
//Mat result = new Mat(320, 212, CvType.CV_8UC1);
Mat result = new Mat(rows, cols, type);
result.put(0, 0, data);
return result;
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} else {
Log.e(TAG, "External Storage not readable.");
}
return null;
}
public static byte[] matStore( Mat mat){
//Log.d(TAG, "matStore - path: "+filePath);
byte[] data=null;
if(isExternalStorageWritable() && mat.isContinuous()){
int cols = mat.cols();
int rows = mat.rows();
int elemSize = (int) mat.elemSize(); // or mat.channels() ?
data= new byte[cols * rows * elemSize];
mat.get(0, 0, data);
Log.e(TAG, "data"+ data);
Log.e(TAG, "mat"+ mat);
} else {
Log.e(TAG, "External Storage not writable.");
}
return data;
}
public static String matToJson(Mat mat){
Log.i(TAG, "matToJson");
JsonObject obj = new JsonObject();
if(mat.isContinuous()){
int cols = mat.cols();
int rows = mat.rows();
int elemSize = (int) mat.elemSize();
byte[] data = new byte[cols * rows * elemSize];
mat.get(0, 0, data);
obj.addProperty("rows", mat.rows());
obj.addProperty("cols", mat.cols());
obj.addProperty("type", mat.type());
String dataString = new String(Base64.encode(data, Base64.DEFAULT));
Log.d(TAG, "matToJson - boooom: "+dataString);
obj.addProperty("data", dataString);
Gson gson = new Gson();
String json = gson.toJson(obj);
return json;
} else {
Log.e(TAG, "Mat not continuous.");
}
return "{}";
}
public static Mat matFromJson(String json){
Log.d(TAG, "matToJson");
JsonParser parser = new JsonParser();
JsonObject JsonObject = parser.parse(json).getAsJsonObject();
int rows = JsonObject.get("rows").getAsInt();
int cols = JsonObject.get("cols").getAsInt();
int type = JsonObject.get("type").getAsInt();
String dataString = JsonObject.get("data").getAsString();
byte[] data = Base64.decode(dataString.getBytes(), Base64.DEFAULT);
Mat mat = new Mat(rows, cols, type);
mat.put(0, 0, data);
Log.e(TAG,"matfromjson"+mat);
return mat;
}
private static byte[] convertInputStreamToByteArray(InputStream inputStream) {
byte[] bytes= null;
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte buff[] = new byte[1024];
int count;
while ((count = inputStream.read(buff)) != -1) {
bos.write(buff, 0, count);
}
bos.flush();
bos.close();
inputStream.close();
bytes = bos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
return bytes;
}
/* Checks if external storage is available for read and write */
public static boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
}
return false;
}
/* Checks if external storage is available to at least read */
public static boolean isExternalStorageReadable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state) ||
Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
return true;
}
return false;
}
public static byte[] getBytes(String ch) {
Mat mat=matFromJson(ch);
//Log.e(TAG,"chaine"+ch);
return matStore(mat);
}
public static Mat getmatfrombyte(byte[] data, int rows, int cols) {
Mat result = new Mat(rows, cols, CvType.CV_8UC1);
result.put(0, 0, data);
return result;
}
public static Mat calculdescriptors(Mat mat){
MatOfKeyPoint points = new MatOfKeyPoint();
FeatureDetector surf = FeatureDetector.create(FeatureDetector.ORB);
DescriptorExtractor extractor = DescriptorExtractor.create(DescriptorExtractor.BRIEF);
surf.detect(mat, points);
int nbrepts= points.toList().size();
Mat descriptors = new Mat();
extractor.compute(mat, points, descriptors);
return descriptors;
}
public static MatOfDMatch matching(Mat matcour,Mat mattrain){
DescriptorMatcher matcher = DescriptorMatcher.create(DescriptorMatcher.BRUTEFORCE_HAMMING);
MatOfDMatch matches = new MatOfDMatch();
matcher.match(matcour, mattrain, matches);
matches.toList();
Log.e(TAG,"matches "+matches.toList());
return filterMatchesByDistance(matches);
}
public static MatOfDMatch filterMatchesByDistance(MatOfDMatch matches){
List<org.opencv.core.DMatch> matches_original = matches.toList();
List<org.opencv.core.DMatch> matches_filtered = new ArrayList<>();
int DIST_LIMIT = 30;
// Check all the matches distance and if it passes add to list of filtered matches
Log.d("DISTFILTER", "ORG SIZE:" + matches_original.size() + "");
for (int i = 0; i < matches_original.size(); i++) {
org.opencv.core.DMatch d = matches_original.get(i);
if (Math.abs(d.distance) <= DIST_LIMIT) {
matches_filtered.add(d);
}
}
Log.d("DISTFILTER", "FIL SIZE:" + matches_filtered.size() + "");
MatOfDMatch mat = new MatOfDMatch();
mat.fromList(matches_filtered);
return mat;
}
}

Related

OpenCV in Android Studio - Haar Cascade - How to check if image is detected

I wrote a program that is used to detect bananas using OpenCV's Haar Cascade method.
public class MainActivity extends Activity implements CvCameraViewListener2 {
private static final String TAG = "OCVSample::Activity";
private static final Scalar BANANA_RECT_COLOR = new Scalar(0, 255, 0, 255);
public static final int JAVA_DETECTOR = 0;
private Mat mRgba;
private Mat mGray;
private File mCascadeFile;
private CascadeClassifier mJavaDetectorBanana;
boolean check = false;
private int mDetectorType = JAVA_DETECTOR;
private String[] mDetectorName;
private float mRelativeBananaSize = 0.2f;
private int mAbsoluteBananaSize = 0;
private CameraBridgeViewBase mOpenCvCameraView;
public Button mSpeechButton;
public TextView checkResults;
double xCenter = -1;
double yCenter = -1;
private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
#Override
public void onManagerConnected(int status) {
switch (status) {
case LoaderCallbackInterface.SUCCESS: {
Log.i(TAG, "OpenCV Loaded Successfully");
try {
InputStream is = getResources().openRawResource(R.raw.banana4th);
File cascadeDir = getDir("cascade", Context.MODE_PRIVATE);
mCascadeFile = new File(cascadeDir, "banana4th.xml");
FileOutputStream os = new FileOutputStream(mCascadeFile);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = is.read(buffer)) != -1) {
os.write(buffer, 0, bytesRead);
}
is.close();
os.close();
mJavaDetectorBanana = new CascadeClassifier(mCascadeFile.getAbsolutePath());
if (mJavaDetectorBanana.empty()) {
Log.e(TAG, "Failed to load cascade classifier");
mJavaDetectorBanana = null;
} else
Log.i(TAG, "Loaded cascade classifier from " + mCascadeFile.getAbsolutePath());
cascadeDir.delete();
} catch (IOException e) {
e.printStackTrace();
Log.e(TAG, "Failed to load cascade. Exception thrown: " + e);
}
mOpenCvCameraView.enableFpsMeter();
mOpenCvCameraView.setCameraIndex(0);
mOpenCvCameraView.enableView();
}
break;
default: {
super.onManagerConnected(status);
}
break;
}
}
};
public MainActivity() {
mDetectorName = new String[2];
mDetectorName[JAVA_DETECTOR] = "Java";
Log.i(TAG, "Instantiated new" + this.getClass());
}
#Override
public void onCreate(Bundle savedInstanceState){
Log.i(TAG,"Called onCreate");
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.activity_main);
mOpenCvCameraView = (CameraBridgeViewBase) findViewById(R.id.fd_activity_surface_view);
mOpenCvCameraView.setCvCameraViewListener(this);
mSpeechButton = (Button) findViewById(R.id.ttsBtn);
checkResults = (TextView) findViewById(R.id.checkResultTB);
Button backButton = (Button) findViewById(R.id.backBtn);
backButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent UIActivity = new Intent(MainActivity.this, UiActivity.class);
startActivity(UIActivity);
}
});
}
#Override
public void onPause() {
super.onPause();
if(mOpenCvCameraView!=null)
mOpenCvCameraView.disableView();
}
#Override
public void onResume() {
super.onResume();
if (!OpenCVLoader.initDebug()) {
Log.d(TAG, "Internal OpenCV library not found. Using OpenCV Manager for initialization");
OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_3_3_0, this, mLoaderCallback);
} else {
Log.d(TAG, "OpenCV library found inside package. Using it!");
mLoaderCallback.onManagerConnected(LoaderCallbackInterface.SUCCESS);
}
}
public void onDestroy() {
super.onDestroy();
mOpenCvCameraView.disableView();
}
public void onCameraViewStarted(int width, int height) {
mGray = new Mat();
mRgba = new Mat();
}
public void onCameraViewStopped() {
mGray.release();
mRgba.release();
}
public Mat onCameraFrame(CvCameraViewFrame inputFrame) {
mRgba = inputFrame.rgba();
mGray = inputFrame.gray();
if (mAbsoluteBananaSize == 0) {
int height = mGray.rows();
if (Math.round(height * mRelativeBananaSize) > 0) {
mAbsoluteBananaSize = Math.round(height * mRelativeBananaSize);
}
}
MatOfRect bananas = new MatOfRect();
if (mDetectorType == JAVA_DETECTOR) {
if (mJavaDetectorBanana != null) {
mJavaDetectorBanana.detectMultiScale(mGray, bananas, 1.1, 2, 2, //TODO: objdetect.CV_HAAR_SCALE_IMAGE)
new Size(mAbsoluteBananaSize, mAbsoluteBananaSize), new Size());
}
} else {
Log.e(TAG, "Detection method is not selected!");
}
Rect[] bananasArray = bananas.toArray();
for (int i = 0; i < bananasArray.length; i++) {
Imgproc.rectangle(mRgba, bananasArray[i].tl(), bananasArray[i].br(), BANANA_RECT_COLOR, 3);
xCenter = (bananasArray[i].x + bananasArray[i].width + bananasArray[i].x) / 2;
yCenter = (bananasArray[i].y + bananasArray[i].height + bananasArray[i].y) / 2;
}
return mRgba;
}
After running the code and a banana is present in the Android device's camera, the banana will be outlined in a rectangle as shown:
Banana Outlined in blue rectangle using the imgproc.rectangle function
After this, I wish to add a button which upon being pressed, will change the text of a textview to say "Banana Detected" if a banana is present on the screen and "Banana Not Detected" if a banana is not present on the screen.
This is where I'm stuck, how do you check if a banana is on screen? I know an if-else must be used but I'm unsure of the conditions needed. Any help is greatly appreciated!
If no bananas are detected, your bananasArray should be empty.
In this case, change the TextView by checking if bananasArray contains data.
(For example, by checking if bananasArray.length > 0)

Capture image rotate after upload

I am uploading image to server but image is rotate after uploaded to server Even preview is showing correct.
So many people facing this problem i found this link but didn't work. And there is many solution but i am not figure out how to fit in my code.
Please help me.
Here is my code
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.fonts.Text.MyTextView;
import com.generalClass.files.UploadFile;
import com.hwindiapp.driver.db.sqLite.DBConnect;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.util.ArrayList;
public class AddVehicleDocActivity extends AppCompatActivity {
private static final int FILE_SELECT_CODE = 124;
private Toolbar mToolbar;
TextView text_header;
MyTextView insuranceHTxt;
MyTextView permitHTxt;
MyTextView vRegHTxt;
MyTextView insNotFoundTxt;
MyTextView permitNotFoundTxt;
MyTextView vRegNotFoundTxt;
DBConnect dbConnect;
Button insBtn;
Button permitBtn;
Button vRegBtn;
LinearLayout insImgVIew;
LinearLayout permitImgVIew;
LinearLayout vRegImgVIew;
String language_labels_get_frm_sqLite = "";
String LBL_DOCUMENTS_TXT_str = "";
String LBL_YOUR_INSURANCE_TXT_str = "";
String LBL_WRONG_FILE_SELECTED_TXT_str = "";
String LBL_LOADING_TXT_str = "";
String LBL_YOUR_PERMIT_TXT_str = "";
String LBL_VEHICLE_REG_TXT_str = "";
String LBL_NOT_FOUND_TXT_str = "";
String LBL_BTN_OK_TXT_str = "";
String LBL_ERROR_TXT_str = "";
String LBL_TRY_AGAIN_LATER_TXT_str = "";
String LBL_DOC_UPLOAD_SUCCESS_TXT_str = "";
String LBL_ADD_TXT_str = "";
String LBL_EDIT_TXT_str = "";
String LBL_SUCCESS_TXT_str = "";
String LBL_BTN_TRIP_CANCEL_CONFIRM_TXT_str = "";
String LBL_NOTE_UPLOAD_DOC_TXT_str = "";
String LBL_CANCEL_TXT_str = "";
String currentDocType = "";
String carJson_str = "";
String vIns = "";
String vPermit = "";
String vReg = "";
android.support.v7.app.AlertDialog alertDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_vehicle_doc);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
dbConnect = new DBConnect(this, "UC_Partner_Labels.db");
text_header = (TextView) findViewById(R.id.text_header);
insuranceHTxt = (MyTextView) findViewById(R.id.insuranceHTxt);
permitHTxt = (MyTextView) findViewById(R.id.permitHTxt);
vRegHTxt = (MyTextView) findViewById(R.id.vRegHTxt);
insNotFoundTxt = (MyTextView) findViewById(R.id.insNotFoundTxt);
permitNotFoundTxt = (MyTextView) findViewById(R.id.permitNotFoundTxt);
vRegNotFoundTxt = (MyTextView) findViewById(R.id.vRegNotFoundTxt);
insImgVIew = (LinearLayout) findViewById(R.id.insImgArea);
permitImgVIew = (LinearLayout) findViewById(R.id.permitImgArea);
vRegImgVIew = (LinearLayout) findViewById(R.id.vRegImgArea);
insBtn = (Button) findViewById(R.id.insBtn);
permitBtn = (Button) findViewById(R.id.permitBtn);
vRegBtn = (Button) findViewById(R.id.vRegBtn);
insBtn.setOnClickListener(new setOnClickAct());
permitBtn.setOnClickListener(new setOnClickAct());
vRegBtn.setOnClickListener(new setOnClickAct());
insImgVIew.setOnClickListener(new setOnClickAct());
permitImgVIew.setOnClickListener(new setOnClickAct());
vRegImgVIew.setOnClickListener(new setOnClickAct());
carJson_str = getIntent().getStringExtra("CarJson");
/* Set Labels */
getLanguageLabelsFrmSqLite();
/* Set Labels Finished */
ImageView back_navigation = (ImageView) findViewById(R.id.back_navigation);
back_navigation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
AddVehicleDocActivity.super.onBackPressed();
}
});
Log.d("carJson_str", ":" + carJson_str);
try {
parseCarJson(carJson_str);
} catch (JSONException e) {
e.printStackTrace();
}
}
public void getLanguageLabelsFrmSqLite() {
Cursor cursor = dbConnect.execQuery("select vValue from labels WHERE vLabel=\"Language_labels\"");
cursor.moveToPosition(0);
language_labels_get_frm_sqLite = cursor.getString(0);
JSONObject obj_language_labels = null;
try {
obj_language_labels = new JSONObject(language_labels_get_frm_sqLite);
LBL_DOCUMENTS_TXT_str = obj_language_labels.getString("LBL_DOCUMENTS_TXT");
LBL_YOUR_INSURANCE_TXT_str = obj_language_labels.getString("LBL_YOUR_INSURANCE_TXT");
LBL_WRONG_FILE_SELECTED_TXT_str = obj_language_labels.getString("LBL_WRONG_FILE_SELECTED_TXT");
LBL_LOADING_TXT_str = obj_language_labels.getString("LBL_LOADING_TXT");
LBL_YOUR_PERMIT_TXT_str = obj_language_labels.getString("LBL_YOUR_PERMIT_TXT");
LBL_VEHICLE_REG_TXT_str = obj_language_labels.getString("LBL_VEHICLE_REG_TXT");
LBL_NOT_FOUND_TXT_str = obj_language_labels.getString("LBL_NOT_FOUND_TXT");
LBL_BTN_OK_TXT_str = obj_language_labels.getString("LBL_BTN_OK_TXT");
LBL_ERROR_TXT_str = obj_language_labels.getString("LBL_ERROR_TXT");
LBL_TRY_AGAIN_LATER_TXT_str = obj_language_labels.getString("LBL_TRY_AGAIN_LATER_TXT");
LBL_DOC_UPLOAD_SUCCESS_TXT_str = obj_language_labels.getString("LBL_DOC_UPLOAD_SUCCESS_TXT");
LBL_ADD_TXT_str = obj_language_labels.getString("LBL_ADD_TXT");
LBL_EDIT_TXT_str = obj_language_labels.getString("LBL_EDIT_TXT");
LBL_SUCCESS_TXT_str = obj_language_labels.getString("LBL_SUCCESS_TXT");
LBL_BTN_TRIP_CANCEL_CONFIRM_TXT_str = obj_language_labels.getString("LBL_BTN_TRIP_CANCEL_CONFIRM_TXT");
LBL_NOTE_UPLOAD_DOC_TXT_str = obj_language_labels.getString("LBL_NOTE_UPLOAD_DOC_TXT");
LBL_CANCEL_TXT_str = obj_language_labels.getString("LBL_CANCEL_TXT");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (obj_language_labels != null) {
text_header.setText("" + LBL_DOCUMENTS_TXT_str);
insuranceHTxt.setText("" + LBL_YOUR_INSURANCE_TXT_str);
permitHTxt.setText("" + LBL_YOUR_PERMIT_TXT_str);
vRegHTxt.setText("" + LBL_VEHICLE_REG_TXT_str);
insNotFoundTxt.setText("" + LBL_NOT_FOUND_TXT_str);
permitNotFoundTxt.setText("" + LBL_NOT_FOUND_TXT_str);
vRegNotFoundTxt.setText("" + LBL_NOT_FOUND_TXT_str);
insBtn.setText(LBL_ADD_TXT_str);
permitBtn.setText(LBL_ADD_TXT_str);
vRegBtn.setText(LBL_ADD_TXT_str);
}
}
public void parseCarJson(String carJson) throws JSONException {
JSONObject obj_profile = new JSONObject(carJson);
vIns = obj_profile.getString("vInsurance");
vPermit = obj_profile.getString("vPermit");
vReg = obj_profile.getString("vRegisteration");
if (vIns == null || vIns.equals("")) {
insNotFoundTxt.setVisibility(View.VISIBLE);
} else {
setDocView(0);
}
if (vPermit == null || vPermit.equals("")) {
permitNotFoundTxt.setVisibility(View.VISIBLE);
} else {
setDocView(1);
}
if (vReg == null || vReg.equals("")) {
vRegNotFoundTxt.setVisibility(View.VISIBLE);
} else {
setDocView(2);
}
}
public void setDocView(int id) {
if (id == 0) {
insNotFoundTxt.setVisibility(View.GONE);
insBtn.setText(LBL_EDIT_TXT_str);
insImgVIew.setVisibility(View.VISIBLE);
} else if (id == 1) {
permitNotFoundTxt.setVisibility(View.GONE);
permitBtn.setText(LBL_EDIT_TXT_str);
permitImgVIew.setVisibility(View.VISIBLE);
} else if (id == 2) {
vRegNotFoundTxt.setVisibility(View.GONE);
vRegBtn.setText(LBL_EDIT_TXT_str);
vRegImgVIew.setVisibility(View.VISIBLE);
}
}
public class setOnClickAct implements View.OnClickListener {
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.insBtn:
currentDocType = "vInsurance";
chooseFIle();
break;
case R.id.permitBtn:
currentDocType = "vPermit";
chooseFIle();
break;
case R.id.vRegBtn:
currentDocType = "vRegisteration";
chooseFIle();
break;
case R.id.insImgArea:
openDocument(vIns);
break;
case R.id.permitImgArea:
openDocument(vPermit);
break;
case R.id.vRegImgArea:
openDocument(vReg);
break;
}
}
}
public void openDocument(String documentName) {
Log.d("Open doc","::"+CommonUtilities.SERVER_URL_VEHICLE_DOCS + getIntent().getStringExtra("iDriverVehicleId") + "/" + documentName);
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(CommonUtilities.SERVER_URL_VEHICLE_DOCS + getIntent().getStringExtra("iDriverVehicleId") + "/" + documentName));
startActivity(browserIntent);
}
public void chooseFIle() {
boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
if (isKitKat) {
Intent intent = new Intent();
intent.setType("*/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, FILE_SELECT_CODE);
} else {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
startActivityForResult(intent, FILE_SELECT_CODE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == FILE_SELECT_CODE) {
Uri uri = data.getData();
// Log.d("Path", "::" + uri.getPath());
// Log.d("Path", "::" + getPath(uri));
String filePath = "";
filePath = (getPath(uri) == null) ? uri.getPath() : getPath(uri);
// Log.d("Ext", ":" + getFileExt(filePath));
final ArrayList<String[]> paramsList = new ArrayList<>();
paramsList.add(generateImageParams("iDriverVehicleId", "" + getIntent().getStringExtra("iDriverVehicleId")));
paramsList.add(generateImageParams("type", "UploadVehicleDoc"));
paramsList.add(generateImageParams("iDriverId", getIntent().getStringExtra("UserID")));
paramsList.add(generateImageParams("DocUploadType", currentDocType));
if (getFileExt(filePath).equalsIgnoreCase("jpg") || getFileExt(filePath).equalsIgnoreCase("gif") || getFileExt(filePath).equalsIgnoreCase("png")
|| getFileExt(filePath).equalsIgnoreCase("jpeg") || getFileExt(filePath).equalsIgnoreCase("bmp") || getFileExt(filePath).equalsIgnoreCase("pdf")
|| getFileExt(filePath).equalsIgnoreCase("doc") || getFileExt(filePath).equalsIgnoreCase("docx")) {
File selectedFile = new File(filePath);
if (selectedFile != null) {
android.support.v7.app.AlertDialog.Builder alertDialogBuilder = new android.support.v7.app.AlertDialog.Builder(
AddVehicleDocActivity.this);
alertDialogBuilder.setTitle(LBL_BTN_TRIP_CANCEL_CONFIRM_TXT_str);
final String finalFilePath = filePath;
alertDialogBuilder
.setMessage(selectedFile.getName() + "\n" + LBL_NOTE_UPLOAD_DOC_TXT_str)
.setCancelable(true)
.setNegativeButton(LBL_CANCEL_TXT_str, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
alertDialog.dismiss();
}
})
.setPositiveButton(LBL_BTN_OK_TXT_str, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
alertDialog.dismiss();
new uploadDocument(finalFilePath, currentDocType + "." + getFileExt(finalFilePath), paramsList).execute();
}
});
alertDialog = alertDialogBuilder.create();
alertDialog.show();
} else {
showMessage(LBL_ERROR_TXT_str, LBL_TRY_AGAIN_LATER_TXT_str);
}
} else {
// showErrorOnSelection();
showMessage(LBL_ERROR_TXT_str, LBL_WRONG_FILE_SELECTED_TXT_str);
}
}
}
}
public String[] generateImageParams(String key, String content) {
String[] tempArr = new String[2];
tempArr[0] = key;
tempArr[1] = content;
return tempArr;
}
public class uploadDocument extends AsyncTask<String, String, String> {
String selectedPath;
String responseString = "";
ProgressDialog myPDialog;
String temp_File_Name = "";
ArrayList<String[]> paramsList;
public uploadDocument(String selectedPath, String temp_File_Name, ArrayList<String[]> paramsList) {
this.selectedPath = selectedPath;
this.temp_File_Name = temp_File_Name;
this.paramsList = paramsList;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
myPDialog = new ProgressDialog(AddVehicleDocActivity.this, R.style.DialogTheme_custom);
myPDialog.setMessage("" + LBL_LOADING_TXT_str);
myPDialog.setCancelable(false);
myPDialog.setCanceledOnTouchOutside(false);
myPDialog.show();
}
#Override
protected String doInBackground(String... strings) {
responseString = new UploadFile().uploadImageAsFile(selectedPath, temp_File_Name, "vFile", paramsList);
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
myPDialog.dismiss();
Log.d("responseString", "::" + responseString);
if (responseString != null && !responseString.equals("")) {
try {
JSONObject obj_temp = new JSONObject(responseString);
String action_str = obj_temp.getString("Action");
String fileName_str = obj_temp.getString("vFileName");
if (action_str.equals("1")) {
showMessage(LBL_SUCCESS_TXT_str, LBL_DOC_UPLOAD_SUCCESS_TXT_str);
JSONObject obj_CarJson = new JSONObject(carJson_str);
if (currentDocType.equals("vInsurance")) {
obj_CarJson.remove("vInsurance");
obj_CarJson.put("vInsurance", fileName_str);
vIns = fileName_str;
setDocView(0);
} else if (currentDocType.equals("vPermit")) {
obj_CarJson.remove("vPermit");
obj_CarJson.put("vPermit", fileName_str);
vPermit = fileName_str;
setDocView(1);
} else if (currentDocType.equals("vRegisteration")) {
obj_CarJson.remove("vRegisteration");
obj_CarJson.put("vRegisteration", fileName_str);
vReg = fileName_str;
setDocView(2);
}
obj_CarJson.remove("eStatus");
obj_CarJson.put("eStatus", "Inactive");
carJson_str = obj_CarJson.toString();
Intent setData = new Intent();
setData.putExtra("CarJson", carJson_str);
setData.putExtra("DriverProfileData", obj_temp.getString("DriverProfileData").toString());
setData.putExtra("iDriverVehicleId", "" + getIntent().getStringExtra("iDriverVehicleId"));
setResult(RESULT_OK, setData);
// Driver_main_profile.updated_json_responseString_profile = obj_profileJson.toString();
//
// Driver_main_profile.driverDocUpdated = true;
} else {
showMessage(LBL_ERROR_TXT_str, LBL_TRY_AGAIN_LATER_TXT_str);
}
} catch (JSONException e) {
e.printStackTrace();
showMessage(LBL_ERROR_TXT_str, LBL_TRY_AGAIN_LATER_TXT_str);
}
} else {
showMessage(LBL_ERROR_TXT_str, LBL_TRY_AGAIN_LATER_TXT_str);
}
}
}
public String getFileExt(String fileName) {
return fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
}
public String getPath(Uri uri) {
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(uri, filePathColumn, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
return filePath;
} else {
return null;
}
}
public void showMessage(String title_str, String content_str) {
android.support.v7.app.AlertDialog.Builder alertDialogBuilder = new android.support.v7.app.AlertDialog.Builder(
AddVehicleDocActivity.this);
alertDialogBuilder.setTitle(title_str);
alertDialogBuilder
.setMessage(content_str)
.setCancelable(true)
.setPositiveButton(LBL_BTN_OK_TXT_str, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
alertDialog.dismiss();
}
});
alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
}
Here is my Upload code
public class UploadFile {
public String uploadImageAsFile(String sourceFileUri, String fileName, String imageParamKey, ArrayList<String[]> params) {
ExifInterface exif = null; //Since API Level 5
try {
exif = new ExifInterface(sourceFileUri);
} catch (IOException e) {
e.printStackTrace();
}
String exifImage = exif.getAttribute(ExifInterface.TAG_ORIENTATION);
String responseString = "";
InputStream inputStream;
try {
inputStream = new FileInputStream(new File(exifImage));
byte[] data;
try {
data = convertToByteArray(inputStream);
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(CommonUtilities.SERVER_URL);
InputStreamBody inputStreamBody = new InputStreamBody(new ByteArrayInputStream(data), fileName);
MultipartEntity multipartEntity = new MultipartEntity(/*HttpMultipartMode.BROWSER_COMPATIBLE,"9999999999", Charset.defaultCharset()*/);
for (int i = 0; i < params.size(); i++) {
String[] paramsArr = params.get(i);
multipartEntity.addPart(paramsArr[0], new StringBody(paramsArr[1]));
}
ContentBody cbFile = new FileBody(new File(exifImage)/*, "multipart/form-data"*/);
multipartEntity.addPart(imageParamKey, cbFile);
httpPost.setEntity(multipartEntity);
// httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "Test Browser");
// httpClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
// httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, org.apache.http.client.params.CookiePolicy.BROWSER_COMPATIBILITY);
// httpPost.setHeader("Content-Type", "multipart/form-data");
// httpPost.setHeader("Content-Type", "image/png");
// httpPost.setHeader("Connection", "Keep-Alive");
// httpPost.setRequestProperty("ENCTYPE", "multipart/form-data");
// httpPost.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
// httpPost.addHeader("Content-Type", "multipart/form-data;charset=UTF-8;boundary=654654");
// httpPost.setHeader("Connection", "Keep-Alive");
// httpPost.setHeader("ENCTYPE", "multipart/form-data");
HttpResponse httpResponse = httpClient.execute(httpPost);
// Handle response back from script.
if (httpResponse != null) {
Log.d("success", "success:" + httpResponse.toString());
responseString = EntityUtils.toString(httpResponse.getEntity());
} else { // Error, no response.
Log.d("Failed", "failed:" + httpResponse.toString());
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
return responseString;
}
private byte[] convertToByteArray(InputStream inputStream) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int next = inputStream.read();
while (next > -1) {
bos.write(next);
next = inputStream.read();
}
bos.flush();
return bos.toByteArray();
}
/**
* #param encodedString
* #return bitmap (from given string)
*/
public Bitmap StringToBitMap(String encodedString){
try{
byte [] encodeByte=Base64.decode(encodedString, Base64.DEFAULT);
Bitmap bitmap=BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
return bitmap;
}catch(Exception e){
e.getMessage();
return null;
}
}
}
You shouldn't rotate the image after upload. You need to rotate it before. The preview is correct maybe because you're respecting Exif values when showing it. But the server isn't.
You need to rotate the image according to it's exif rotation:
https://stackoverflow.com/a/20480741/3410697
And only then you should upload it to the server
Call this function where you get path of image
public void setImage(String _path) {
int orientation = CustomImageUtil.getExifOrientation(_path);
BitmapFactory.Options resample = new BitmapFactory.Options();
resample.inSampleSize = 4;
Bitmap bitmap = BitmapFactory.decodeFile(_path, resample);
if (orientation == 90) {
bitmap = CustomImageUtil.rotate(bitmap, 90);
} else if (orientation == 180) {
bitmap = CustomImageUtil.rotate(bitmap, 180);
} else if (orientation == 270) {
bitmap = CustomImageUtil.rotate(bitmap, 270);
}
// use your bitmap here
}
CustomImageUtil.class:
public class CustomImageUtil {
public static String getRealPathFromURI(Context context,Uri contentURI) {
String result;
Cursor cursor = context.getContentResolver().query(contentURI, null, null, null, null);
if (cursor == null) { // Source is Dropbox or other similar local file path
result = contentURI.getPath();
} else {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
result = cursor.getString(idx);
cursor.close();
}
return result;
}
// method for bitmap to base64
public static String encodeTobase64(Bitmap image) {
Bitmap immage = image;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
immage.compress(Bitmap.CompressFormat.PNG, 60, baos);
byte[] b = baos.toByteArray();
String imageEncoded = Base64.encodeToString(b, Base64.DEFAULT);
Log.d("Image Log:", imageEncoded);
return imageEncoded;
}
/**
* getExifOrientation -- Roate the image on the right angel
* #param filepath -- path of the file to be rotated
* #return
*/
public static int getExifOrientation(String filepath) {
int degree = 0;
ExifInterface exif = null;
try {
exif = new ExifInterface(filepath);
} catch (IOException ex) {ex.printStackTrace();
}
if (exif != null) {
int orientation = exif.getAttributeInt(
ExifInterface.TAG_ORIENTATION, -1);
if (orientation != -1) {
// We only recognize a subset of orientation tag values.
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
degree = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
degree = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
degree = 270;
break;
}
}
}
return degree;
}
// Rotates the bitmap by the specified degree.
// If a new bitmap is created, the original bitmap is recycled.
public static Bitmap rotate(Bitmap b, int degrees) {
if (degrees != 0 && b != null) {
Matrix m = new Matrix();
m.setRotate(degrees, (float) b.getWidth() / 2,
(float) b.getHeight() / 2);
try {
Bitmap b2 = Bitmap.createBitmap(b, 0, 0, b.getWidth(),
b.getHeight(), m, true);
if (b != b2) {
b.recycle();
b = b2;
}
} catch (OutOfMemoryError ex) {ex.printStackTrace();
}
}
return b;
}
}
To convert Bitmap to Uri
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}

Displaying Images from Sd Card but taking time in android

Hi in the below I am displaying images from sdcard.sdcard means storing into locally.but while privew the images it was showing some black color after image got displaying.
want to display smooth preview with black screen.i am unable to figure out the issue.can any one help me.
java
public class ImageGallery extends Activity {
Bundle bundle;
String catid, temp, responseJson;
JSONObject json;
ImageView imageViewPager;
// for parsing
JSONObject o1, o2;
JSONArray a1, a2;
int k;
Boolean toggleTopBar;
ArrayList<String> imageThumbnails;
ArrayList<String> imageFull;
public static int imagePosition=0;
SubsamplingScaleImageView imageView, imageViewPreview, fullImage ;
ImageView thumb1, back;
private LinearLayout thumb2;
RelativeLayout topLayout, stripeView;
RelativeLayout thumbnailButtons;
FrameLayout gridFrame;
//SharedPreferences data
SharedPreferences s1;
SharedPreferences.Editor editor;
int swipeCounter;
ParsingForFinalImages parsingObject;
int position_grid;
SharedPreferences p;
Bitmap bm;
int numOfImagesInsidee;
LinearLayout backLinLayout;
public static boolean isThumb2=false;
public static boolean isThumb1=false;
public static ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_gallery);
//isThumb2=false;
toggleTopBar = false;
//position_grid=getIntent().getExtras().getInt("position");
thumbnailButtons = (RelativeLayout)findViewById(R.id.thumbnailButtons);
topLayout = (RelativeLayout)findViewById(R.id.topLayout);
//fullImage = (SubsamplingScaleImageView)findViewById(R.id.fullimage);
backLinLayout = (LinearLayout)findViewById(R.id.lin_back);
backLinLayout.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent io = new Intent(getBaseContext(), MainActivity.class);
// clear the previous activity and start a new task
// System.gc();
// io.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(io);
finish();
}
});
ConnectionDetector cd = new ConnectionDetector(getBaseContext());
Boolean isInternetPresent = cd.isConnectingToInternet();
thumb1 = (ImageView)findViewById(R.id.thumb1);
thumb2 = (LinearLayout)findViewById(R.id.thumb2);
stripeView = (RelativeLayout)findViewById(R.id.stripeView) ;
gridFrame = (FrameLayout)findViewById(R.id.gridFrame);
thumb1.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View view) {
stripeView.setVisibility(View.GONE);
gridFrame.setVisibility(View.VISIBLE);
viewPager.setVisibility(View.GONE);
//fullImage.setVisibility(View.GONE);
thumb1.setClickable(false);
isThumb1=true;
isThumb2=false;
Log.i("Thumb Position 1",""+ImageGallery.imagePosition);
viewPager.removeAllViews();
Fragment newFragment = new GridFragment2();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.gridFrame, newFragment).commit();
}
});
thumb2.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View view) {
// stripeView.setVisibility(View.VISIBLE);
stripeView.setVisibility(View.GONE);
gridFrame.setVisibility(View.VISIBLE);
viewPager.setVisibility(View.GONE);
// fullImage.setVisibility(View.GONE);
thumb1.setClickable(true);
isThumb2=true;
isThumb1=false;
Log.i("Thumb Position 2",""+ImageGallery.imagePosition);
viewPager.removeAllViews();
Fragment newFragment = new ImageStripeFragment();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.gridFrame, newFragment).commit();
}
});
// allow networking on main thread
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
/*bundle = getIntent().getExtras();
catid = bundle.getString("catid");*/
// Toast.makeText(getBaseContext(), catid, Toast.LENGTH_LONG).show();
// making json using the catalogue id we got
p = getSharedPreferences("gridData", Context.MODE_APPEND);
catid = p.getString("SelectedCatalogueIdFromGrid1", "");
int clickedListPos = p.getInt("clickedPosition", 0);
imageViewPreview = (SubsamplingScaleImageView)findViewById(R.id.preview);
imageThumbnails = new ArrayList<String>();
imageFull = new ArrayList<String>();
s1 = this.getSharedPreferences("data", Context.MODE_APPEND);
editor = s1.edit();
Log.d("catidfnl", catid);
numOfImagesInsidee = p.getInt("numberOfItemsSelectedFromGrid1", 0);
Log.d("blingbling2", String.valueOf(numOfImagesInsidee));
// adding downloaded images to arraylist
for(int m=0;m<numOfImagesInsidee;m++){
imageThumbnails.add(Environment.getExternalStorageDirectory()+"/"+"thumbImage" + catid + m+".png");
imageFull.add(Environment.getExternalStorageDirectory()+"/"+"fullImage" + catid + m+".png");
// imageFull.add("file://" + Environment.getExternalStorageDirectory() + "/" + "fullImage32.png");
}
viewPager = (ViewPager) findViewById(R.id.pager);
ImagePagerAdapter adapter = new ImagePagerAdapter();
viewPager.setAdapter(adapter);
// SubsamplingScaleImageView fullImage = new SubsamplingScaleImageView(ImageGallery.this);
// code to display image in a horizontal strip starts here
LinearLayout layout = (LinearLayout) findViewById(R.id.linear);
for (int i = 0; i < imageThumbnails.size(); i++) {
imageView = new SubsamplingScaleImageView(this);
imageView.setId(i);
imageView.setPadding(2, 2, 2, 2);
// Picasso.with(this).load("file://"+imageThumbnails.get(i)).into(imageView);
// imageView.setScaleType(ImageView.ScaleType.FIT_XY);
layout.addView(imageView);
ViewGroup.LayoutParams params = imageView.getLayoutParams();
params.width = 200;
params.height = 200;
imageView.setLayoutParams(params);
imageView.setZoomEnabled(false);
imageView.setDoubleTapZoomScale(0);
imageView.setImage(ImageSource.uri(imageThumbnails.get(0)));
imageView.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View view) {
imageView.setZoomEnabled(false);
imageViewPreview.setImage(ImageSource.uri(imageFull.get(view.getId())));
imageView.recycle();
imageViewPreview.recycle();
}
});
}
// code to display image in a horizontal strip ends here
imageViewPreview.setZoomEnabled(false);
/*imageViewPreview.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View view) {
imageViewPreview.setZoomEnabled(false);
stripeView.setVisibility(View.GONE);
gridFrame.setVisibility(View.GONE);
viewPager.setVisibility(View.VISIBLE);
}
});*/
imageViewPreview.setOnClickListener(new DoubleClickListener() {
#Override
public void onSingleClick(View v) {
Log.d("yo click", "single");
}
#Override
public void onDoubleClick(View v) {
Log.d("yo click", "double");
}
});
}
public abstract class DoubleClickListener implements View.OnClickListener {
private static final long DOUBLE_CLICK_TIME_DELTA = 300;//milliseconds
long lastClickTime = 0;
#Override
public void onClick(View v) {
long clickTime = System.currentTimeMillis();
if (clickTime - lastClickTime < DOUBLE_CLICK_TIME_DELTA){
onDoubleClick(v);
} else {
onSingleClick(v);
}
lastClickTime = clickTime;
}
public abstract void onSingleClick(View v);
public abstract void onDoubleClick(View v);
}
// #Override
// public void onBackPressed() {
// Intent io = new Intent(getBaseContext(), MainActivity.class);
// // clear the previous activity and start a new task
// super.onBackPressed();
// finish();
// // System.gc();
// // io.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
// startActivity(io);
// }
#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_image_gallery, 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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class ImagePagerAdapter extends PagerAdapter {
/* private int[] mImages = new int[] {
R.drawable.scroll3,
R.drawable.scroll1,
R.drawable.scroll2,
R.drawable.scroll4
};*/
/* private String[] description=new String[]
{
"One","two","three","four"
};
*/
#Override
public int getCount() {
Log.i("Image List Size", "" + imageFull.size());
return imageFull.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((SubsamplingScaleImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Context context = ImageGallery.this;
SubsamplingScaleImageView fullImage = new SubsamplingScaleImageView(ImageGallery.this);
// for placeholder
// fullImage.setImage(ImageSource.resource(R.drawable.tan2x));
if(!GridFragment2.isSelectedGrid2&&!ImageStripeFragment.isImageStripe) {
imagePosition = position;
fullImage.setImage(ImageSource.uri(imageFull.get(imagePosition)));
}
/* else if(!ImageStripeFragment.isImageStripe)
{
imagePosition = position;
fullImage.setImage(ImageSource.uri(imageFull.get(imagePosition)));
}
else if(ImageStripeFragment.isImageStripe)
{
position=imagePosition;
viewPager.setCurrentItem(imagePosition);
fullImage.setImage(ImageSource.uri(imageFull.get(position)));
}*/
else
{
position=imagePosition;
viewPager.setCurrentItem(imagePosition);
fullImage.setImage(ImageSource.uri(imageFull.get(position)));
//viewPager.removeAllViews();
}
// ImageView imageViewPager = new ImageView(context);
// ImageView imageViewPager = new ImageView(getApplicationContext());
// SubsamplingScaleImageView fullImage = new SubsamplingScaleImageView(ImageGallery.this);
GridFragment2.isSelectedGrid2=false;
ImageStripeFragment.isImageStripe=false;
// Log.i("Image Resource", "" + ImageSource.uri(imageFull.get(position)));
// imageViewPager.setImageBitmap(BitmapFactory.decodeFile(imageFull.get(position)));
// imageViewPager.setImageBitmap(myBitmap);
// fullImage.setImage(ImageSource.bitmap(bmImg));
//imageView.setImageResource(Integer.parseInt(imageFull.get(position)));
/*int padding = context.getResources().getDimensionPixelSize(
R.dimen.padding_medium);
imageView.setPadding(padding, padding, padding, padding);*/
/*imageView.setScaleType(ImageView.ScaleType.CENTER);
imageView.setImageResource(Integer.parseInt(imageFull.get(position)));
if(position==3)
{
}*/
// Log.i("Image Position",""+position);
/*text.setText(description[position]);
Log.i("Text Position",""+position);*/
/*switch(position)
{
case 0:
String pos=String.valueOf(position);
text.setText(pos);
break;
case 1:
String pos1=String.valueOf(position);
text.setText(pos1);
break;
case 2:
String pos2=String.valueOf(position);
text.setText(pos2);
break;
case 3:
String pos3=String.valueOf(position);
text.setText(pos3);
break;
}*/
fullImage.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View view) {
if (toggleTopBar == false) {
// thumbnailButtons.setVisibility(View.GONE);
thumbnailButtons.animate()
.translationY(-2000)
.setDuration(1000)
.start();
toggleTopBar = true;
} else if (toggleTopBar == true) {
// thumbnailButtons.setVisibility(View.VISIBLE);
thumbnailButtons.animate()
.translationY(0)
.setDuration(1000)
.start();
toggleTopBar = false;
}
}
});
((ViewPager) container).addView(fullImage, 0);
return fullImage;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((SubsamplingScaleImageView) object);
}
/* #Override
public void destroyItem(View collection, int position, Object o) {
Log.d("DESTROY", "destroying view at position " + position);
View view = (View) o;
((ViewPager) collection).removeView(view);
view = null;
}*/
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
}
use this ImageLoader Class
public class ImageLoader {
MemoryCache memoryCache = new MemoryCache();
FileCache fileCache;
private Map<ImageView, String> imageViews = Collections
.synchronizedMap(new WeakHashMap<ImageView, String>());
ExecutorService executorService;
Handler handler = new Handler();// handler to display images in UI thread
int stub_id;
int widht;
public ImageLoader(Context context, int stub_idx) {
fileCache = new FileCache(context);
executorService = Executors.newFixedThreadPool(5);
stub_id = stub_idx;
}
public void DisplayImage(String url, ImageView imageView, int widht, ProgressBar bar) {
this.widht = widht;
imageViews.put(imageView, url);
Bitmap bitmap = memoryCache.get(url);
if (bitmap != null)
{
bar.setVisibility(View.GONE);
imageView.setImageBitmap(bitmap);
}
else {
queuePhoto(url, imageView, widht, bar);
imageView.setImageResource(stub_id);
}
}
private void queuePhoto(String url, ImageView imageView, int w, ProgressBar bar) {
PhotoToLoad p = new PhotoToLoad(url, imageView, bar);
executorService.submit(new PhotosLoader(p, w));
}
public Bitmap getBitmap(String url, int w) {
File f = fileCache.getFile(url);
// from SD cache
Bitmap b = decodeFile(f, w);
if (b != null)
return b;
// from web
try {
Bitmap bitmap = null;
URL imageUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) imageUrl
.openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setInstanceFollowRedirects(true);
InputStream is = conn.getInputStream();
OutputStream os = new FileOutputStream(f);
Utils.CopyStream(is, os);
os.close();
conn.disconnect();
bitmap = decodeFile(f, w);
return bitmap;
} catch (Throwable ex) {
ex.printStackTrace();
if (ex instanceof OutOfMemoryError)
memoryCache.clear();
return null;
}
}
// decodes image and scales it to reduce memory consumption
private Bitmap decodeFile(File f, int w) {
try {
// decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
FileInputStream stream1 = new FileInputStream(f);
BitmapFactory.decodeStream(stream1, null, o);
stream1.close();
// Find the correct scale value. It should be the power of 2.
final int REQUIRED_SIZE = w;
System.out.println("screen wdth " + widht);
int width_tmp = o.outWidth, height_tmp = o.outHeight;
System.out.println("image with === " + width_tmp);
int scale = 1;
while (true) {
if (width_tmp / 2 < REQUIRED_SIZE
|| height_tmp / 2 < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
FileInputStream stream2 = new FileInputStream(f);
Bitmap bitmap = BitmapFactory.decodeStream(stream2, null, o2);
stream2.close();
return bitmap;
}
catch (FileNotFoundException e) {
Log.e(e.getMessage(), "");
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
// Task for the queue
private class PhotoToLoad {
public String url;
public ImageView imageView;
public ProgressBar bar;
public PhotoToLoad(String u, ImageView i, ProgressBar progressBar) {
url = u;
imageView = i;
bar = progressBar;
}
}
class PhotosLoader implements Runnable {
PhotoToLoad photoToLoad;
int w;
PhotosLoader(PhotoToLoad photoToLoad, int w) {
this.photoToLoad = photoToLoad;
this.w = w;
}
#Override
public void run() {
try {
if (imageViewReused(photoToLoad))
return;
Bitmap bmp = getBitmap(photoToLoad.url, w);
memoryCache.put(photoToLoad.url, bmp);
if (imageViewReused(photoToLoad))
return;
BitmapDisplayer bd = new BitmapDisplayer(bmp, photoToLoad);
handler.post(bd);
} catch (Throwable th) {
th.printStackTrace();
}
}
}
boolean imageViewReused(PhotoToLoad photoToLoad) {
String tag = imageViews.get(photoToLoad.imageView);
return tag == null || !tag.equals(photoToLoad.url);
}
// Used to display bitmap in the UI thread
class BitmapDisplayer implements Runnable {
Bitmap bitmap;
PhotoToLoad photoToLoad;
public BitmapDisplayer(Bitmap b, PhotoToLoad p) {
bitmap = b;
photoToLoad = p;
}
public void run() {
if (imageViewReused(photoToLoad))
return;
if (bitmap != null)
photoToLoad.imageView.setImageBitmap(bitmap);
else
photoToLoad.imageView.setImageResource(stub_id);
photoToLoad.bar.setVisibility(View.GONE);
}
}
public void clearCache() {
memoryCache.clear();
fileCache.clear();
}
Then make new class for File cache
public class FileCache {
private File cacheDir;
public FileCache(Context context) {
// Find the dir to save cached images
if (android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED))
cacheDir = new File(
android.os.Environment.getExternalStorageDirectory(),
"LazyList");
else
//cacheDir = url.getCacheDir();
if (!cacheDir.exists())
cacheDir.mkdirs();
}
public File getFile(String url) {
// I identify images by hashcode. Not a perfect solution, good for the
// demo.
String filename = String.valueOf(url.hashCode());
// Another possible solution (thanks to grantland)
// String filename = URLEncoder.encode(url);
File f = new File(cacheDir, filename);
return f;
}
public void clear() {
File[] files = cacheDir.listFiles();
if (files == null)
return;
for (File f : files)
f.delete();
}
}
Then last make Memory cache class , all three seperatly class
public class MemoryCache {
private static final String TAG = "MemoryCache";
private Map<String, Bitmap> cache=Collections.synchronizedMap(
new LinkedHashMap<String, Bitmap>(10,1.5f,true));//Last argument true for LRU ordering
private long size=0;//current allocated size
private long limit=1000000;//max memory in bytes
public MemoryCache(){
//use 25% of available heap size
setLimit(Runtime.getRuntime().maxMemory()/4);
}
public void setLimit(long new_limit){
limit=new_limit;
Log.i(TAG, "MemoryCache will use up to "+limit/1024./1024.+"MB");
}
public Bitmap get(String id){
try{
if(!cache.containsKey(id))
return null;
//NullPointerException sometimes happen here http://code.google.com/p/osmdroid/issues/detail?id=78
return cache.get(id);
}catch(NullPointerException ex){
ex.printStackTrace();
return null;
}
}
public void put(String id, Bitmap bitmap){
try{
if(cache.containsKey(id))
size-=getSizeInBytes(cache.get(id));
cache.put(id, bitmap);
size+=getSizeInBytes(bitmap);
checkSize();
}catch(Throwable th){
th.printStackTrace();
}
}
private void checkSize() {
Log.i(TAG, "cache size="+size+" length="+cache.size());
if(size>limit){
Iterator<Entry<String, Bitmap>> iter=cache.entrySet().iterator();//least recently accessed item will be the first one iterated
while(iter.hasNext()){
Entry<String, Bitmap> entry=iter.next();
size-=getSizeInBytes(entry.getValue());
iter.remove();
if(size<=limit)
break;
}
Log.i(TAG, "Clean cache. New size "+cache.size());
}
}
public void clear() {
try{
//NullPointerException sometimes happen here http://code.google.com/p/osmdroid/issues/detail?id=78
cache.clear();
size=0;
}catch(NullPointerException ex){
ex.printStackTrace();
}
}
long getSizeInBytes(Bitmap bitmap) {
if(bitmap==null)
return 0;
return bitmap.getRowBytes() * bitmap.getHeight();
}

ListView scrolling Slow even using backThread to load images

My ImageCache
public class ImageCache {
private static ImageCache instance;
private Context mContext;
private HashMap<Chat, Boolean> isContain = new HashMap<Chat, Boolean>();
private static Bitmap defaultBitmap;
private int loginId;
private WorkQueue workQueue;
private LruCache<Chat, Bitmap> cache = new LruCache<Chat, Bitmap>(
(int) getMaxSize()) {
#SuppressLint("NewApi")
protected int sizeOf(Chat key, Bitmap value) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1) {
return value.getByteCount();
} else {
return value.getRowBytes() * value.getHeight();
}
}
protected Bitmap create(Chat ChatKey) {
if (Looper.myLooper() == Looper.getMainLooper()) {
Log.i("getView", "main thread");
return null;
}
Log.i("getView", "image cache");
// if(Thread.currentThread().getName().equals("main")){
// return null;
// }
Bitmap bitmap = null;
if (ChatKey.getMsgType() == Chat.TYPE_IMAGE) {
bitmap = getImageThumbnail(ChatKey);
synchronized (isContain) {
isContain.put(ChatKey, true);
}
return bitmap;
}
bitmap = getVideoThumbnail(ChatKey);
synchronized (isContain) {
isContain.put(ChatKey, true);
}
return bitmap;
}
#Override
protected void entryRemoved(boolean evicted, Chat key, Bitmap oldValue,
Bitmap newValue) {
super.entryRemoved(evicted, key, oldValue, newValue);
synchronized (isContain) {
isContain.put(key, false);
}
oldValue.recycle();
if (evicted) {
}
}
};
private Bitmap getVideoThumbnail(Chat chat) {
if (chat.isPending()) {
return getVideoThumbnail(chat.getFilePath());
}
if (loginId == chat.getSenderID()) {
DataBaseHandler baseHandler = new DataBaseHandler(mContext);
String fIlePath = baseHandler.getSentMsgFIlePath(chat.getMsgID());
if (fIlePath != null) {
return getVideoThumbnail(fIlePath);
}
}
File file = new File(Util.videoDir, chat.getMsgID()
+ Util.getExtension(chat.getChatContent()));
if (!file.exists()) {
file = new File(Util.thumbnails, chat.getMsgID() + "");
if (!file.exists()) {
Util.downloadThumbnail(chat);
if (!file.exists()) {
return null;
}
}
return BitmapFactory.decodeFile(file.getAbsolutePath());
}
return getVideoThumbnail(file.getAbsolutePath());
}
private Bitmap getImageThumbnail(Chat chat) {
if (chat.isPending()) {
return getImageThumbnail(chat.getFilePath());
}
if (loginId == chat.getSenderID()) {
DataBaseHandler baseHandler = new DataBaseHandler(mContext);
String fIlePath = baseHandler.getSentMsgFIlePath(chat.getMsgID());
if (fIlePath != null) {
return getImageThumbnail(fIlePath);
}
}
File file = new File(Util.imageDir, chat.getMsgID() + "");
if (!file.exists()) {
file = new File(Util.thumbnails, chat.getMsgID() + "");
if (!file.exists()) {
Util.downloadThumbnail(chat);
if (!file.exists()) {
return null;
}
}
Bitmap image = BitmapFactory.decodeFile(file.getAbsolutePath());
return image;
}
return getImageThumbnail(file.getAbsolutePath());
}
private Bitmap getImageThumbnail(String imagePath) {
BitmapFactory.Options options = new Options();
options.inPreferredConfig = Config.RGB_565;
Bitmap image = null;
if (imagePath == null) {
return null;
}
Cursor cursor = mContext.getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
new String[] { MediaStore.Video.Media._ID },
new String(MediaStore.Video.Media.DATA + "=?"),
new String[] { imagePath }, null);
if (cursor.getCount() > 0) {
cursor.moveToFirst();
image = MediaStore.Images.Thumbnails.getThumbnail(
mContext.getContentResolver(), cursor.getInt(0),
Thumbnails.MICRO_KIND, options);
cursor.close();
return image;
}
cursor.close();
return null;
}
private Bitmap getVideoThumbnail(String imagePath) {
Bitmap image = null;
BitmapFactory.Options options = new Options();
options.inPreferredConfig = Config.RGB_565;
Cursor cursor = mContext.getContentResolver().query(
MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
new String[] { MediaStore.Video.Media._ID },
new String(MediaStore.Video.Media.DATA + "=?"),
new String[] { imagePath }, null);
if (cursor.getCount() > 0) {
cursor.moveToFirst();
image = MediaStore.Video.Thumbnails.getThumbnail(
mContext.getContentResolver(), cursor.getInt(0),
Thumbnails.MICRO_KIND, null);
cursor.close();
return image;
}
cursor.close();
return null;
}
private ImageCache(Context context) {
mContext = context.getApplicationContext();
loginId = Util.getSharedPref(mContext).getInt(C.LOGIN_USER_ID, -1);
defaultBitmap = BitmapFactory.decodeResource(mContext.getResources(),
R.drawable.image);
workQueue = WorkQueue.getInstance(context);
}
public static ImageCache getInstance(Context context) {
if (instance == null) {
instance = new ImageCache(context);
}
return instance;
}
private long getMaxSize() {
return Runtime.getRuntime().totalMemory() / 4;
}
public boolean isBitmapLoaded(Chat key) {
synchronized (isContain) {
if (isContain.get(key) == null) {
return false;
}
return isContain.get(key);
}
}
public void getImage(Chat key){
cache.get(key);
}
public Bitmap getBitmap(Chat key) {
if (isBitmapLoaded(key)) {
return cache.get(key);
}
workQueue.addRequest(key);
return defaultBitmap;
}
public void remove(Chat key) {
cache.remove(key);
isContain.put(key, false);
}
public void evictAll() {
cache.evictAll();
}
}
My workqueue
public class WorkQueue {
private final int MAX_THREAD = 1;
private WorkerThread[] threads;
private ArrayList<Chat> queue;
private static WorkQueue instance;
private ImageCache imageCache;
private ImageLoadListner imageLoadListner;
private WorkQueue(Context context) {
threads = new WorkerThread[MAX_THREAD];
for (int i = 0; i < MAX_THREAD; i++) {
threads[i] = new WorkerThread();
threads[i].start();
}
queue = new ArrayList<Chat>();
}
public void setImageCache(ImageCache imageCache){
this.imageCache=imageCache;
}
public static WorkQueue getInstance(Context context) {
if (instance == null) {
instance = new WorkQueue(context);
}
return instance;
}
public void addRequest(Chat key) {
synchronized (queue) {
if(queue.contains(key)){
return;
}
if(queue.size()==20){
queue.remove(0);
}
queue.add(key);
queue.notify();
}
}
public void setImageLoadListner(ImageLoadListner listner) {
this.imageLoadListner = listner;
}
private class WorkerThread extends Thread {
#Override
public void run() {
super.run();
setName("Background");
synchronized (queue) {
if (queue.size() == 0) {
try {
queue.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
while (queue.size() > 0) {
Chat chat = queue.get(0);
imageCache.getImage(chat);
imageLoadListner.onImageLoad(chat);
synchronized (queue) {
queue.remove(0);
if (queue.size() == 0) {
try {
queue.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
}
I am calling getBitmap(key) from getView() of adapter and notify the adapter when an image load by calling the onIMageLoad() of adapter from workqueqe. Calling imagecache create from backthread even then LOg in create() of imageCache is printing and listView scrolling very slow due to the bitmap creating on backThread.
Hanish U should use LinkedList WorkQueue forprivate ArrayList<Chat> queue; because in linked list addition or deletion is very fast, and save the image id in Chat object because you are doing double work for fetching the Thumbnil first get the Image id on path than get the thumb.
and for Video u can use directly without changing your code
ThumbnailUtils.public static Bitmap createVideoThumbnail (String filePath, int kind)

open cv error(fatal signal 11) if images converted to grayscale

I know its related to heap of device but it even crashes when i use very small images.And i tried it on samsung grand,motog,karbonn titanium s1.It crashes everywhere>is there a way to handle it.The only thing iam doing is first converting the images to gray scale and then compare.if i compare images without converting to grayscale it works fine no matter how big is image.
here is my code--
main activity
public class MainActivity extends Activity {
private static final String TAG = "OCVSample::Activity";
private static Bitmap bmp, yourSelectedImage, bmpimg1, bmpimg2;
private static ImageView iv1, iv2;
private static TextView tv;
private static String path1, path2;
private static String text;
private static Button start;
private static int imgNo = 0;
private static Uri selectedImage;
private static InputStream imageStream;
private static long startTime, endTime;
private static final int SELECT_PHOTO = 100;
//private static int descriptor = DescriptorExtractor.BRISK;
private static int descriptor = DescriptorExtractor.SIFT;
private static String descriptorType;
private static int min_dist = 10;
private static int min_matches = 750;
public MainActivity() {
Log.i(TAG, "Instantiated new " + this.getClass());
}
private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
#Override
public void onManagerConnected(int status) {
switch (status) {
case LoaderCallbackInterface.SUCCESS: {
Log.i(TAG, "OpenCV loaded successfully");
doTask1(iv1,true);
doTask1(iv2, false);
}
break;
default: {
super.onManagerConnected(status);
}
break;
}
}
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
Log.i(TAG, "called onCreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv1 = (ImageView) MainActivity.this.findViewById(R.id.img1);
iv2 = (ImageView) MainActivity.this.findViewById(R.id.img2);
start = (Button) MainActivity.this.findViewById(R.id.button1);
tv = (TextView) MainActivity.this.findViewById(R.id.tv);
OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_4, this,
mLoaderCallback);
run();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_settings:
Intent call = new Intent(MainActivity.this, Settings.class);
call.putExtra("descriptor", descriptor);
call.putExtra("min_dist", min_dist);
call.putExtra("min_matches", min_matches);
call.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
call.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(call);
break;
}
return true;
}
public void run() {
if (descriptor == DescriptorExtractor.BRIEF)
descriptorType = "BRIEF";
else if (descriptor == DescriptorExtractor.BRISK)
descriptorType = "BRISK";
else if (descriptor == DescriptorExtractor.FREAK)
descriptorType = "FREAK";
else if (descriptor == DescriptorExtractor.ORB)
descriptorType = "ORB";
else if (descriptor == DescriptorExtractor.SIFT)
descriptorType = "SIFT";
else if(descriptor == DescriptorExtractor.SURF)
descriptorType = "SURF";
System.out.println(descriptorType);
tv.setText("Select the two images to be compared.\n"+"DescriptorExtractor:"+descriptorType+"\nHamming distance between descriptors:"+min_dist+"\nMinimum number of good matches:"+min_matches);
iv1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, SELECT_PHOTO);
imgNo = 1;
}
});
iv2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, SELECT_PHOTO);
imgNo = 2;
}
});
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (bmpimg1 != null && bmpimg2 != null) {
/*if(bmpimg1.getWidth()!=bmpimg2.getWidth()){
bmpimg2 = Bitmap.createScaledBitmap(bmpimg2, bmpimg1.getWidth(), bmpimg1.getHeight(), true);
}*/
bmpimg1 = Bitmap.createScaledBitmap(bmpimg1, 100, 100, true);
bmpimg2 = Bitmap.createScaledBitmap(bmpimg2, 100, 100, true);
Mat img1 = new Mat();
Utils.bitmapToMat(bmpimg1, img1);
Mat img2 = new Mat();
Utils.bitmapToMat(bmpimg2, img2);
Imgproc.cvtColor(img1, img1, Imgproc.COLOR_RGBA2GRAY);
Imgproc.cvtColor(img2, img2, Imgproc.COLOR_RGBA2GRAY);
img1.convertTo(img1, CvType.CV_32F);
img2.convertTo(img2, CvType.CV_32F);
//Log.d("ImageComparator", "img1:"+img1.rows()+"x"+img1.cols()+" img2:"+img2.rows()+"x"+img2.cols());
Mat hist1 = new Mat();
Mat hist2 = new Mat();
MatOfInt histSize = new MatOfInt(180);
MatOfInt channels = new MatOfInt(0);
ArrayList<Mat> bgr_planes1= new ArrayList<Mat>();
ArrayList<Mat> bgr_planes2= new ArrayList<Mat>();
Core.split(img1, bgr_planes1);
Core.split(img2, bgr_planes2);
MatOfFloat histRanges = new MatOfFloat (0f, 180f);
boolean accumulate = false;
Imgproc.calcHist(bgr_planes1, channels, new Mat(), hist1, histSize, histRanges, accumulate);
Core.normalize(hist1, hist1, 0, hist1.rows(), Core.NORM_MINMAX, -1, new Mat());
Imgproc.calcHist(bgr_planes2, channels, new Mat(), hist2, histSize, histRanges, accumulate);
Core.normalize(hist2, hist2, 0, hist2.rows(), Core.NORM_MINMAX, -1, new Mat());
img1.convertTo(img1, CvType.CV_32F);
img2.convertTo(img2, CvType.CV_32F);
hist1.convertTo(hist1, CvType.CV_32F);
hist2.convertTo(hist2, CvType.CV_32F);
double compare = Imgproc.compareHist(hist1, hist2, Imgproc.CV_COMP_CHISQR);
Log.v("ImageComparator", "compare: "+compare);
if(compare>0 && compare<1500) {
Toast.makeText(MainActivity.this, "Images may be possible duplicates, verifying", Toast.LENGTH_LONG).show();
new asyncTask(MainActivity.this).execute();
}
else if(compare==0)
Toast.makeText(MainActivity.this, "Images are exact duplicates", Toast.LENGTH_LONG).show();
else
Toast.makeText(MainActivity.this, "Images are not duplicates", Toast.LENGTH_LONG).show();
startTime = System.currentTimeMillis();
} else
Toast.makeText(MainActivity.this,
"You haven't selected images.", Toast.LENGTH_LONG)
.show();
}
});
}
#Override
protected void onNewIntent(Intent newIntent) {
super.onNewIntent(newIntent);
min_dist = newIntent.getExtras().getInt("min_dist");
descriptor = newIntent.getExtras().getInt("descriptor");
min_matches = newIntent.getExtras().getInt("min_matches");
run();
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode) {
case SELECT_PHOTO:
if (resultCode == RESULT_OK) {
try{
selectedImage = imageReturnedIntent.getData();
try {
imageStream = getContentResolver().openInputStream(
selectedImage);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
yourSelectedImage = BitmapFactory.decodeStream(imageStream);
if (imgNo == 1) {
iv1.setImageBitmap(yourSelectedImage);
path1 = selectedImage.getPath();
bmpimg1 = yourSelectedImage;
iv1.invalidate();
} else if (imgNo == 2) {
iv2.setImageBitmap(yourSelectedImage);
path2 = selectedImage.getPath();
bmpimg2 = yourSelectedImage;
iv2.invalidate();
}
}
catch(OutOfMemoryError exception){
Toast.makeText(getBaseContext(), exception.getMessage().toString(), Toast.LENGTH_SHORT).show();
}
catch (NullPointerException e) {
// TODO: handle exception
Toast.makeText(getBaseContext(), "Image cant be selected", Toast.LENGTH_SHORT);
}
}
}
}
#Override
public void onPause() {
super.onPause();
}
#Override
public void onResume() {
super.onResume();
OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_4, this, // My changes
mLoaderCallback);
}
public static class asyncTask extends AsyncTask<Void, Void, Void> {
private static Mat img1, img2, descriptors, dupDescriptors;
private static FeatureDetector detector;
private static DescriptorExtractor DescExtractor;
private static DescriptorMatcher matcher;
private static MatOfKeyPoint keypoints, dupKeypoints;
private static MatOfDMatch matches, matches_final_mat;
private static ProgressDialog pd;
private static boolean isDuplicate = false;
private MainActivity asyncTaskContext=null;
private static Scalar RED = new Scalar(255,0,0);
private static Scalar GREEN = new Scalar(0,255,0);
public asyncTask(MainActivity context)
{
asyncTaskContext=context;
}
#Override
protected void onPreExecute() {
pd = new ProgressDialog(asyncTaskContext);
pd.setIndeterminate(true);
pd.setCancelable(true);
pd.setCanceledOnTouchOutside(false);
pd.setMessage("Processing...");
pd.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
compare();
return null;
}
#Override
protected void onPostExecute(Void result) {
try {
Mat img3 = new Mat();
MatOfByte drawnMatches = new MatOfByte();
Features2d.drawMatches(img1, keypoints, img2, dupKeypoints,
matches_final_mat, img3, GREEN, RED, drawnMatches, Features2d.NOT_DRAW_SINGLE_POINTS);
bmp = Bitmap.createBitmap(img3.cols(), img3.rows(),
Bitmap.Config.ARGB_8888);
Imgproc.cvtColor(img3, img3, Imgproc.COLOR_BGR2RGB);
Utils.matToBitmap(img3, bmp);
List<DMatch> finalMatchesList = matches_final_mat.toList();
final int matchesFound=finalMatchesList.size();
endTime = System.currentTimeMillis();
if (finalMatchesList.size() > min_matches)// dev discretion for
// number of matches to
// be found for an image
// to be judged as
// duplicate
{
text = finalMatchesList.size()
+ " matches were found. Possible duplicate image.\nTime taken="
+ (endTime - startTime) + "ms";
isDuplicate = true;
} else {
text = finalMatchesList.size()
+ " matches were found. Images aren't similar.\nTime taken="
+ (endTime - startTime) + "ms";
isDuplicate = false;
}
pd.dismiss();
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(
asyncTaskContext);
alertDialog.setTitle("Result");
alertDialog.setCancelable(false);
LayoutInflater factory = LayoutInflater.from(asyncTaskContext);
final View view = factory.inflate(R.layout.image_view, null);
ImageView matchedImages = (ImageView) view
.findViewById(R.id.finalImage);
matchedImages.setImageBitmap(bmp);
matchedImages.invalidate();
final CheckBox shouldBeDuplicate = (CheckBox) view
.findViewById(R.id.checkBox);
TextView message = (TextView) view.findViewById(R.id.message);
message.setText(text);
alertDialog.setView(view);
shouldBeDuplicate
.setText("These images are actually duplicates.");
alertDialog.setPositiveButton("Add to logs",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
File logs = new File(Environment
.getExternalStorageDirectory()
.getAbsolutePath()
+ "/imageComparator/Data Logs.txt");
FileWriter fw;
BufferedWriter bw;
try {
fw = new FileWriter(logs, true);
bw = new BufferedWriter(fw);
bw.write("Algorithm used: "
+ descriptorType
+ "\nHamming distance: "
+ min_dist + "\nMinimum good matches: "+min_matches
+"\nMatches found: "+matchesFound+"\nTime elapsed: "+(endTime-startTime)+"seconds\n"+ path1
+ " was compared to " + path2
+ "\n" + "Is actual duplicate: "
+ shouldBeDuplicate.isChecked()
+ "\nRecognized as duplicate: "
+ isDuplicate + "\n");
bw.close();
Toast.makeText(
asyncTaskContext,
"Logs updated.\nLog location: "
+ Environment
.getExternalStorageDirectory()
.getAbsolutePath()
+ "/imageComparator/Data Logs.txt",
Toast.LENGTH_LONG).show();
} catch (IOException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
try {
File dir = new File(Environment
.getExternalStorageDirectory()
.getAbsolutePath()
+ "/imageComparator/");
dir.mkdirs();
logs.createNewFile();
logs = new File(
Environment
.getExternalStorageDirectory()
.getAbsolutePath()
+ "/imageComparator/Data Logs.txt");
fw = new FileWriter(logs, true);
bw = new BufferedWriter(fw);
bw.write("Algorithm used: "
+ descriptorType
+ "\nMinimum distance between keypoints: "
+ min_dist + "\n" + path1
+ " was compared to " + path2
+ "\n"
+ "Is actual duplicate: "
+ shouldBeDuplicate.isChecked()
+ "\nRecognized as duplicate: "
+ isDuplicate + "\n");
bw.close();
Toast.makeText(
asyncTaskContext,
"Logs updated.\nLog location: "
+ Environment
.getExternalStorageDirectory()
.getAbsolutePath()
+ "/imageComparator/Data Logs.txt",
Toast.LENGTH_LONG).show();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
});
alertDialog.show();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(asyncTaskContext, e.toString(),
Toast.LENGTH_LONG).show();
}
}
void compare() {
try {
bmpimg1 = bmpimg1.copy(Bitmap.Config.ARGB_8888, true);
bmpimg2 = bmpimg2.copy(Bitmap.Config.ARGB_8888, true);
img1 = new Mat();
img2 = new Mat();
Utils.bitmapToMat(bmpimg1, img1);
Utils.bitmapToMat(bmpimg2, img2);
Imgproc.cvtColor(img1, img1, Imgproc.COLOR_BGR2RGB);
Imgproc.cvtColor(img2, img2, Imgproc.COLOR_BGR2RGB);
detector = FeatureDetector.create(FeatureDetector.PYRAMID_FAST);
DescExtractor = DescriptorExtractor.create(descriptor);
matcher = DescriptorMatcher
.create(DescriptorMatcher.BRUTEFORCE_HAMMING);
keypoints = new MatOfKeyPoint();
dupKeypoints = new MatOfKeyPoint();
descriptors = new Mat();
dupDescriptors = new Mat();
matches = new MatOfDMatch();
detector.detect(img1, keypoints);
Log.d("LOG!", "number of query Keypoints= " + keypoints.size());
detector.detect(img2, dupKeypoints);
Log.d("LOG!", "number of dup Keypoints= " + dupKeypoints.size());
// Descript keypoints
DescExtractor.compute(img1, keypoints, descriptors);
DescExtractor.compute(img2, dupKeypoints, dupDescriptors);
Log.d("LOG!", "number of descriptors= " + descriptors.size());
Log.d("LOG!",
"number of dupDescriptors= " + dupDescriptors.size());
// matching descriptors
matcher.match(descriptors, dupDescriptors, matches);
Log.d("LOG!", "Matches Size " + matches.size());
// New method of finding best matches
List<DMatch> matchesList = matches.toList();
List<DMatch> matches_final = new ArrayList<DMatch>();
for (int i = 0; i < matchesList.size(); i++) {
if (matchesList.get(i).distance <= min_dist) {
matches_final.add(matches.toList().get(i));
}
}
matches_final_mat = new MatOfDMatch();
matches_final_mat.fromList(matches_final);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void doTask1(ImageView iv,boolean iv_flag) {
Bitmap bitmap=null;
if(iv_flag){
bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.download);
}
else{
bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
}
Log.d(TAG, "bitmap: " + bitmap.getWidth() + "x" + bitmap.getHeight());
bitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);
Log.d(TAG, "bitmap 8888: " + bitmap.getWidth() + "x" + bitmap.getHeight());
//GrabCut part
Mat img = new Mat();
Utils.bitmapToMat(bitmap, img);
Log.d(TAG, "img: " + img);
int r = img.rows();
int c = img.cols();
Point p1 = new Point(c/10, r/10);
Point p2 = new Point(c-c/10, r-r/10);
Rect rect = new Rect(p1, p2);
Log.d(TAG, "rect: " + rect);
Mat mask = new Mat();
Mat fgdModel = new Mat();
Mat bgdModel = new Mat();
Mat imgC3 = new Mat();
Imgproc.cvtColor(img, imgC3, Imgproc.COLOR_RGBA2RGB);
Log.d(TAG, "imgC3: " + imgC3);
Log.d(TAG, "Grabcut begins");
Imgproc.grabCut(imgC3, mask, rect, bgdModel, fgdModel, 2, Imgproc.
GC_INIT_WITH_RECT);
Log.d(TAG, "Grabcut ends");
Log.d(TAG, "mask: " + mask);
Log.d(TAG, "bgdModel: " + bgdModel);
Log.d(TAG, "fgdModel: " + fgdModel);
Core.convertScaleAbs(mask, mask, 100, 0);
Imgproc.cvtColor(mask, mask, Imgproc.COLOR_GRAY2RGBA);
Log.d(TAG, "maskC4: " + mask);
//convert to Bitmap
Log.d(TAG, "Convert to Bitmap");
//Utils.matToBitmap(imgC3, bitmap);
Utils.matToBitmap(mask, bitmap);
iv.setImageBitmap(bitmap);
if(iv_flag)
bmpimg1=bitmap;
else
bmpimg2=bitmap;
//release MAT part
img.release();
imgC3.release();
mask.release();
fgdModel.release();
bgdModel.release();
}
}
settings activity---
public class Settings extends Activity {
#SuppressWarnings("unused")
private static RadioGroup descTypes;
private static RadioButton brief, brisk, freak, orb;
private static Button apply;
private static EditText DIST_LIMIT, MIN_MATCHES;
private static int descriptor, min_dist, min_matches;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
descTypes = (RadioGroup) findViewById(R.id.radioGroup1);
brief = (RadioButton) findViewById(R.id.radio0);
brisk = (RadioButton) findViewById(R.id.radio1);
freak = (RadioButton) findViewById(R.id.radio2);
orb = (RadioButton) findViewById(R.id.radio3);
apply = (Button) findViewById(R.id.button1);
DIST_LIMIT = (EditText) findViewById(R.id.editText1);
MIN_MATCHES = (EditText) findViewById(R.id.editText2);
MIN_MATCHES.setText("100");
DIST_LIMIT.setText("80");
apply.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int descriptor = 0, min_dist = 80, min_matches=100;
if (brief.isChecked())
descriptor = DescriptorExtractor.BRIEF;
else if (brisk.isChecked())
descriptor = DescriptorExtractor.BRISK;
else if (freak.isChecked())
descriptor = DescriptorExtractor.FREAK;
else if (orb.isChecked())
descriptor = DescriptorExtractor.ORB;
try {
min_dist = Integer.parseInt(DIST_LIMIT.getText().toString());
} catch (Exception e) {
e.printStackTrace();
min_dist = 500;
}
Intent call = new Intent(Settings.this, MainActivity.class);
call.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
call.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
call.putExtra("descriptor", descriptor);
call.putExtra("min_dist", min_dist);
call.putExtra("min_matches", min_matches);
startActivity(call);
}
});
}
#Override
protected void onNewIntent(Intent newIntent) {
super.onNewIntent(newIntent);
descriptor = newIntent.getExtras().getInt("descriptor");
min_dist = newIntent.getExtras().getInt("min_dist");
min_matches = newIntent.getExtras().getInt("min_matches");
DIST_LIMIT.setText(min_dist + "");
switch (descriptor) {
case 3:
orb.setChecked(true);
break;
case 4:
brief.setChecked(true);
break;
case 5:
brisk.setChecked(true);
break;
case 6:
freak.setChecked(true);
break;
}
apply.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (brief.isChecked())
descriptor = DescriptorExtractor.BRIEF;
else if (brisk.isChecked())
descriptor = DescriptorExtractor.BRISK;
else if (freak.isChecked())
descriptor = DescriptorExtractor.FREAK;
else if (orb.isChecked())
descriptor = DescriptorExtractor.ORB;
try {
min_dist = Integer.parseInt(DIST_LIMIT.getText().toString());
min_matches = Integer.parseInt(MIN_MATCHES.getText().toString());
} catch (Exception e) {
e.printStackTrace();
min_dist = 80;
min_matches=100;
}
Intent call = new Intent(Settings.this, MainActivity.class);
call.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
call.putExtra("descriptor", descriptor);
call.putExtra("min_dist", min_dist);
call.putExtra("min_matches", min_matches);
startActivity(call);
}
});
}
}
and the logcat---
08-22 18:44:11.919: V/ImageComparator(24384): compare: 48.32461247119096
08-22 18:44:12.139: D/LOG!(24384): number of query Keypoints= 1x65
08-22 18:44:12.139: D/LOG!(24384): number of dup Keypoints= 1x62
08-22 18:44:12.139: A/libc(24384): Fatal signal 11 (SIGSEGV) at 0x00000000 (code=1), thread 24587 (AsyncTask #1)

Categories

Resources