Android chat application emoji's issue - android

I am working on Android chat application. Now I want to send emoji's in my chat module. How can i implement emoji' in chat application? Please guide me for this app. If there is any API for this app then also suggest me. Thanks
public void callAsynchronousTask() {
final Handler handler = new Handler();
timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
try {
new GetSingleChat(Chat_Detail_Single.this).execute(friend_id);
} catch (NullPointerException e) {
}
}
});
}
};
timer.schedule(doAsynchronousTask, 1000, 1000);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btncamera:
Dialog_Manager.chooseImage(Chat_Detail_Single.this, "singlechat");
break;
case R.id.img_back:
timer.cancel();
finish();
break;
case R.id.btnsend:
String message_ = edt_mes.getText().toString();
if (message_.replace(" ", "").length() == 0) {
} else {
edt_mes.setText("");
new Send_chat_message(Chat_Detail_Single.this).execute(SharedPref.getUserID(this), friend_id, "mes", message_);
}
break;
}
}
public static void get_chat_data(List<Chat_prop> fetch_chat) {
MyCustomList.clear();
MyCustomList.addAll(fetch_chat);
try {
if (adptor == null) {
adptor = new Single_Chat_Adap(activity,
MyCustomList);
Chat_Detail_Single.listView.setAdapter(adptor);
Chat_Detail_Single.listView.setSelection(MyCustomList
.size() - 1);
lastCount = MyCustomList.size();
} else {
if (lastCount != MyCustomList.size()) {
lastCount = MyCustomList.size();
adptor.notifyDataSetChanged();
Chat_Detail_Single.listView
.setSelection(MyCustomList.size());
}
}
} catch (NullPointerException e) {
} catch (Exception e) {
// TODO: handle exception
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (requestCode == Dialog_Manager.Gallery_Intent
&& resultCode == RESULT_OK && data != null) {
File direct = new File(
Environment.getExternalStorageDirectory() + "/Fun You");
if (!direct.exists()) {
if (direct.mkdir())
;
}
long time = System.currentTimeMillis();
capturepath1 = direct.getAbsolutePath() + "/" + time + ".jpg";
File file = new File(capturepath1);
Uri outputFileUri = Uri.fromFile(file);
Uri selectedImage = data.getData();
imagePath = getPath(selectedImage);
Intent cropIntent = new Intent("com.android.camera.action.CROP");
Uri contentUri = selectedImage;
cropIntent.setDataAndType(contentUri, "image/*");
cropIntent.putExtra("crop", "true");
cropIntent.putExtra("aspectX", 1);
cropIntent.putExtra("aspectY", 1);
cropIntent.putExtra("outputX", 1000);
cropIntent.putExtra("outputY", 1000);
cropIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
cropIntent.putExtra("return-data", true);
startActivityForResult(cropIntent, 3);
} else if (requestCode == Dialog_Manager.Camera_Intent
&& resultCode == RESULT_OK) {
File direct = new File(
Environment.getExternalStorageDirectory() + "/Fun You");
if (!direct.exists()) {
if (direct.mkdir())
;
}
long time = System.currentTimeMillis();
capturepath1 = direct.getAbsolutePath() + "/" + time + ".jpg";
File file = new File(capturepath1);
Uri outputFileUri = Uri.fromFile(file);
File photos = new File(imagePath);
Uri selectedImage = Uri.fromFile(photos);
Intent cropIntent = new Intent("com.android.camera.action.CROP");
Uri contentUri = selectedImage;
cropIntent.setDataAndType(contentUri, "image/*");
cropIntent.putExtra("crop", "true");
cropIntent.putExtra("aspectX", 1);
cropIntent.putExtra("aspectY", 1);
cropIntent.putExtra("outputX", 1000);
cropIntent.putExtra("outputY", 1000);
cropIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
cropIntent.putExtra("return-data", true);
startActivityForResult(cropIntent, 3);
} else if (requestCode == 3) {
try {
Bitmap thumbnail = null;
Bundle extras = data.getExtras();
if (extras != null) {
thumbnail = extras.getParcelable("data");
Bitmap bm = thumbnail;
bm = ExtraMethods.decodeFile(capturepath1);
bm = ExifUtils.rotateBitmap(capturepath1, bm);
// new Uplaod_image().execute(capturepath1);
new Send_chat_message(Chat_Detail_Single.this).execute(SharedPref.getUserID(this), friend_id, "image", capturepath1);
}
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e + "", Toast.LENGTH_LONG)
.show();
}
}
public String getPath(Uri uri) {
if (uri == null) {
return null;
}
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(uri, projection, null, null,
null);
if (cursor != null) {
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
return uri.getPath();
}

There is no specific api available to implement and send emojis. You can achieve this using ImageSpan objects. The TextViews and EditTexts use Spanned/Spannable objects to store the entered text content, not just mere Java Strings. On these Spanned/Spannable objects you can define spans for sections on the text that modifies the way that those sections are shown. So you can display images in place of certain sections.
Check the docs:
Also, I found a blog, it might be helpful for you.

This Library is all you need to implement Emojicons. Just don't forget to change your TextViews and EditTexts to this Library's EmojiconTextViews and EmojiconEditTexts respectively.
Hope this helps.

You need to encode emoji before upload.
in this way you encode emoji to UTF code
try {
String mystring = URLEncoder.encode(strComments, HTTP.UTF_8);
param.add(new BasicNameValuePair("comment", mystring));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
for decoding
enter code here
try {
String Title = URLDecoder.decode(comment, "UTF-8");
holder.tvComment.setText(Title);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}

Related

how to compress the bitmap image?

I want to upload image to the server. Converted my image as bitmap but still getting error. Bitmap too large to be uploaded into a texture
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == this.RESULT_CANCELED) {
return;
}
if (requestCode == GALLERY) {
if (data != null) {
contentURI = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(contentURI, filePathColumn, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
if (l == 0) {
imagePath = cursor.getString(columnIndex);
}
}
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), contentURI);
String path = saveImage(bitmap);
Toast.makeText(SignUpActivity.this, "Image Saved!", Toast.LENGTH_SHORT).show();
BitmapDrawable bdrawable = new BitmapDrawable(this.getResources(), bitmap);
if (l == 0) {
captureAadhar.setBackground(bdrawable);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
else if (requestCode == CAMERA) {
//if (checkPermissionREAD_EXTERNAL_STORAGE(this)) {
// do your stuff..
if (data != null) {
contentURI = data.getData();
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, null, null, null);
int column_index_data = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToLast();
if (l == 0) {
imagePath = cursor.getString(column_index_data);
}
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
BitmapDrawable bdrawable = new BitmapDrawable(this.getResources(), thumbnail);
if (l == 0) {
captureAadhar.setBackground(bdrawable);
}
saveImage(thumbnail);
Toast.makeText(SignUpActivity.this, "Image Saved!", Toast.LENGTH_SHORT).show();
}
If i get picture using gallery means I am getting error as "Bitmap too large to be uploaded into a texture"
and if i get picture using camera means getting error as
"Caused by: java.lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaProvider uri content://media/external/images/media from pid=18253, uid=10257 requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()"
public String saveImage(Bitmap myBitmap) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
myBitmap.compress( Bitmap.CompressFormat.JPEG, 90, bytes );
wallpaperDirectory = new File( Environment.getExternalStorageDirectory() + IMAGE_DIRECTORY );
// have the object build the directory structure, if needed.
if (!wallpaperDirectory.exists()) {
wallpaperDirectory.mkdirs();
}
try {
f = new File( wallpaperDirectory, Calendar.getInstance().getTimeInMillis() + ".jpg" );
f.createNewFile();
FileOutputStream fo = new FileOutputStream( f );
fo.write( bytes.toByteArray() );
MediaScannerConnection.scanFile( this, new String[]{f.getPath()}, new String[]{"image/jpeg"}, null );
fo.close();
Log.d( "TAG", "File Saved::--->" + f.getAbsolutePath() );
return f.getAbsolutePath();
} catch (IOException e1) {
e1.printStackTrace();
}
return "";
}
Try this, link to library
https://github.com/Tourenathan-G5organisation/SiliCompressor
/**
* Request Permission for writing to External Storage in 6.0 and up
*/
private void requestPermissions(int mediaType) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
if (mediaType == TYPE_IMAGE) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
MY_PERMISSIONS_REQUEST_WRITE_STORAGE);
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
MY_PERMISSIONS_REQUEST_WRITE_STORAGE_VID);
}
} else {
if (mediaType == TYPE_IMAGE) {
// Want to compress an image
dispatchTakePictureIntent();
} else if (mediaType == TYPE_VIDEO) {
// Want to compress a video
dispatchTakeVideoIntent();
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_WRITE_STORAGE: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
dispatchTakePictureIntent();
} else {
Toast.makeText(this, "You need to enable the permission for External Storage Write" +
" to test out this library.", Toast.LENGTH_LONG).show();
return;
}
break;
}
case MY_PERMISSIONS_REQUEST_WRITE_STORAGE_VID: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
dispatchTakeVideoIntent();
} else {
Toast.makeText(this, "You need to enable the permission for External Storage Write" +
" to test out this library.", Toast.LENGTH_LONG).show();
return;
}
break;
}
default:
}
}
private File createMediaFile(int type) throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String fileName = (type == TYPE_IMAGE) ? "JPEG_" + timeStamp + "_" : "VID_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(
type == TYPE_IMAGE ? Environment.DIRECTORY_PICTURES : Environment.DIRECTORY_MOVIES);
File file = File.createTempFile(
fileName, /* prefix */
type == TYPE_IMAGE ? ".jpg" : ".mp4", /* suffix */
storageDir /* directory */
);
// Get the path of the file created
mCurrentPhotoPath = file.getAbsolutePath();
Log.d(LOG_TAG, "mCurrentPhotoPath: " + mCurrentPhotoPath);
return file;
}
private void dispatchTakePictureIntent() {
/*Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");*/
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
takePictureIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createMediaFile(TYPE_IMAGE);
} catch (IOException ex) {
// Error occurred while creating the File
Log.d(LOG_TAG, "Error occurred while creating the file");
}
// Continue only if the File was successfully created
if (photoFile != null) {
// Get the content URI for the image file
capturedUri = FileProvider.getUriForFile(this,
FILE_PROVIDER_AUTHORITY,
photoFile);
Log.d(LOG_TAG, "Log1: " + String.valueOf(capturedUri));
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, capturedUri);
startActivityForResult(takePictureIntent, REQUEST_TAKE_CAMERA_PHOTO);
}
}
}
private void dispatchTakeVideoIntent() {
Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
takeVideoIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
if (takeVideoIntent.resolveActivity(getPackageManager()) != null) {
try {
takeVideoIntent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 10);
takeVideoIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
capturedUri = FileProvider.getUriForFile(this,
FILE_PROVIDER_AUTHORITY,
createMediaFile(TYPE_VIDEO));
takeVideoIntent.putExtra(MediaStore.EXTRA_OUTPUT, capturedUri);
Log.d(LOG_TAG, "VideoUri: " + capturedUri.toString());
startActivityForResult(takeVideoIntent, REQUEST_TAKE_VIDEO);
} catch (IOException e) {
e.printStackTrace();
}
}
}
// Method which will process the captured image
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//verify if the image was gotten successfully
if (requestCode == REQUEST_TAKE_CAMERA_PHOTO && resultCode == Activity.RESULT_OK) {
new ImageCompressionAsyncTask(this).execute(mCurrentPhotoPath,
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/Silicompressor/images");
} else if (requestCode == REQUEST_TAKE_VIDEO && resultCode == RESULT_OK) {
if (data.getData() != null) {
//create destination directory
File f = new File( Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES) + "/Silicompressor/videos");
if (f.mkdirs() || f.isDirectory())
//compress and output new video specs
new VideoCompressAsyncTask(this).execute(mCurrentPhotoPath, f.getPath());
}
}
}
class ImageCompressionAsyncTask extends AsyncTask {
Context mContext;
public ImageCompressionAsyncTask(Context context) {
mContext = context;
}
#Override
protected String doInBackground(String... params) {
String filePath = SiliCompressor.with(mContext).compress(params[0], new File(params[1]));
return filePath;
/*
Bitmap compressBitMap = null;
try {
compressBitMap = SiliCompressor.with(mContext).getCompressBitmap(params[0], true);
return compressBitMap;
} catch (IOException e) {
e.printStackTrace();
}
return compressBitMap;
*/
}
#Override
protected void onPostExecute(String s) {
/*
if (null != s){
imageView.setImageBitmap(s);
int compressHieght = s.getHeight();
int compressWidth = s.getWidth();
float length = s.getByteCount() / 1024f; // Size in KB;
String text = String.format("Name: %s\nSize: %fKB\nWidth: %d\nHeight: %d", "ff", length, compressWidth, compressHieght);
picDescription.setVisibility(View.VISIBLE);
picDescription.setText(text);
}
*/
File imageFile = new File(s);
compressUri = Uri.fromFile(imageFile);
//FileProvider.getUriForFile(mContext, mContext.getApplicationContext().getPackageName()+ FILE_PROVIDER_EXTENTION, imageFile);
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), compressUri);
imageView.setImageBitmap(bitmap);
String name = imageFile.getName();
float length = imageFile.length() / 1024f; // Size in KB
int compressWidth = bitmap.getWidth();
int compressHieght = bitmap.getHeight();
String text = String.format(Locale.US, "Name: %s\nSize: %fKB\nWidth: %d\nHeight: %d", name, length, compressWidth, compressHieght);
picDescription.setVisibility(View.VISIBLE);
picDescription.setText(text);
} catch (IOException e) {
e.printStackTrace();
}
}
}
As for loading large bimaps, read docs: https://developer.android.com/topic/performance/graphics/load-bitmap
Basically, you should provide inSampleSize to load load scaled version. Don't try to decode large bitmap without scaling, this will fail.

Not able to upload image from camera in android

I am working on an app in which I want to get image from gallery or camera and then send it to server using multipart. I am able to send picture from gallery to server but when I tried to send image from camera it shows me failure.
// code for the same
// code fro open camera
private void cameraIntent() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
}
// on activity result
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CAMERA) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
Log.d("TAG", "onActivityResult: "+Uri.fromFile(destination));
filePath = destination.toString();
if (filePath != null) {
try {
execMultipartPost();
} catch (Exception e) {
e.printStackTrace();
}
} else {
Toast.makeText(getActivity(), "Image not capturd!", Toast.LENGTH_LONG).show();
}
}
// send to server code
private void execMultipartPost() throws Exception {
File file = new File(filePath);
String contentType = file.toURL().openConnection().getContentType();
Log.d("TAG", "file new path: " + file.getPath());
Log.d("TAG", "contentType: " + contentType);
RequestBody fileBody = RequestBody.create(MediaType.parse(contentType), file);
final String filename = "file_" + System.currentTimeMillis() / 1000L;
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("date", "21-09-2017")
.addFormDataPart("time", "11.56")
.addFormDataPart("description", "hello")
.addFormDataPart("image", filename + ".jpg", fileBody)
.build();
Log.d("TAG", "execMultipartPost: "+requestBody);
okhttp3.Request request = new okhttp3.Request.Builder()
.url("http://myexample/api/user/lets_send")
.post(requestBody)
.build();
OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, final IOException e) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getActivity(), "nah", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onResponse(Call call, final okhttp3.Response response) throws IOException {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
try {
Log.d("TAG", "response of image: " + response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
});
}
Try This, it may help
Intent takePhotoIntent= new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Date date = new Date();
String timeStamp = new SimpleDateFormat(pictureNameDateFormat, Locale.US).format(date.getTime());
File fileDirectory = new File(Environment.getExternalStorageDirectory() + "/Pictures");
if (fileDirectory.exists()) {
takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(
new File(Environment.getExternalStorageDirectory() + "/Pictures/picture_"+ timeStamp + ".png")));
takePhotoIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
takePhotoIntent.setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
if (takePhotoIntent.resolveActivity(activity.getPackageManager()) != null) {
activity.startActivityForResult(takeVideoIntent, captureVideoActivityRequestCode);
}
}
private void onCaptureImageResult(Intent data) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Log.e("path",Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
}
Please use below code to capture image by camera and for pick image from gallery and you can crop also.
First of all please add this dependency in your build.gradle
compile 'com.theartofdev.edmodo:android-image-cropper:2.3.+'
In your Activity please add this code :
uploadPic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onSelectImageClick(view);
}
});
/**
* Start pick image activity with chooser.
*/
public void onSelectImageClick(View view) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(AccountSettingActivity.this, android.Manifest.permission.CAMERA) + ContextCompat.checkSelfPermission(AccountSettingActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(AccountSettingActivity.this, new String[]{android.Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE}, MY_REQUEST_CAMERA);
} else if (ContextCompat.checkSelfPermission(AccountSettingActivity.this, android.Manifest.permission.CAMERA) + ContextCompat.checkSelfPermission(AccountSettingActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
CropImage.startPickImageActivity(this);
}
}else {
CropImage.startPickImageActivity(this);
}
}
#Override
#SuppressLint("NewApi")
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// handle result of pick image chooser
if (requestCode == CropImage.PICK_IMAGE_CHOOSER_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
Uri imageUri = CropImage.getPickImageResultUri(this, data);
startCropImageActivity(imageUri);
}
// handle result of CropImageActivity
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
fileUri = result.getUri();
userImage.setImageURI(result.getUri());
Toast.makeText(this, "Cropping successful, Sample: " + result.getSampleSize(), Toast.LENGTH_LONG).show();
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Toast.makeText(this, "Cropping failed: " + result.getError(), Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED ) {
CropImage.startPickImageActivity(this);
} else {
Toast.makeText(this, "Cancelling, required permissions are not granted", Toast.LENGTH_LONG).show();
}
}
/**
* Start crop image activity for the given image.
*/
private void startCropImageActivity(Uri imageUri) {
CropImage.activity(imageUri)
.setGuidelines(CropImageView.Guidelines.ON)
.setMultiTouchEnabled(true)
.start(this);
}
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
in manifest please add these permissions and ask for run time permissions also ,this may solve your problem ,Your coding is correct those works for me perfectly after adding permission.
Please go trough the following code
try {
if (imageUri != null) {
photo = BitmapFactory.decodeStream(getActivity().getContentResolver().openInputStream(imageUri));
} else {
photo = (Bitmap) data.getExtras().get("data");
}
Uri tempUri = CommonData.getImageUri(getContext(), photo);
uri = tempUri.toString();
String path = CommonData.convertImageUriToFile(tempUri, getActivity());
// new PreprocessImagesTask().execute(path);
showLoader();
new ProcessingImage(this).execute(path);
} catch (Exception e) {
e.printStackTrace();
}
public static Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
public static String convertImageUriToFile(Uri imageUri, Activity activity) {
String imgPath = "";
String Path;
try {
Cursor cursor = null;
int imageID = 0;
try {
/* ********** Which columns values want to get ****** */
String[] proj = {
MediaStore.Images.Media.DATA,
MediaStore.Images.Media._ID,
MediaStore.Images.Thumbnails._ID,
MediaStore.Images.ImageColumns.ORIENTATION
};
cursor = activity.getContentResolver().query(
imageUri, // Get data for specific image URI
proj, // Which columns to return
null, // WHERE clause; which rows to return (all rows)
null, // WHERE clause selection arguments (none)
null // Order-by clause (ascending by name)
);
int file_ColumnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
int size = cursor.getCount();
/* ****** If size is 0, there are no images on the SD Card. **** */
if (size == 0) {
// imageDetails.setText("No Image");
} else {
int thumbID = 0;
if (cursor.moveToFirst()) {
Path = cursor.getString(file_ColumnIndex);
//String orientation = cursor.getString(orientation_ColumnIndex);
String CapturedImageDetails = " CapturedImageDetails : \n\n"
+ " ImageID :" + imageID + "\n"
+ " ThumbID :" + thumbID + "\n"
+ " Path :" + Path + "\n";
showLog("CapturedImageDetails", CapturedImageDetails);
imgPath = Path;
// Show Captured Image detail on view
// imageDetails.setText(CapturedImageDetails);
}
}
} finally {
if (cursor != null) {
cursor.close();
}
}
return "" + imgPath;
} catch (IllegalArgumentException e) {
e.printStackTrace();
return "";
}
}
Give a try!
private static final int REQUEST_IMAGE = 100;
private static final String TAG = "MainActivity";
TextView imgPath;
ImageView picture;
File destination;
String imagePath;
//onCreate
private void cameraIntent() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(destination));
startActivityForResult(intent, REQUEST_IMAGE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if( requestCode == REQUEST_IMAGE && resultCode == Activity.RESULT_OK ){
try {
FileInputStream in = new FileInputStream(destination);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 10;
imagePath = destination.getAbsolutePath();//get your path
imgPath.setText(imagePath);
Bitmap bmp = BitmapFactory.decodeStream(in, null, options);
picture.setImageBitmap(bmp);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
else{
imgPath.setText("Request cancelled");
}
}

how to show image in image view

I am working on android custom camera application when i click on gallery view it show mobile default gallery and show photos that i clicked but i want when i click on gallery then clicked image show in my custom view how can i implement
public void clickedGallery(View view) {
if (MyDebug.LOG)
Log.d(TAG, "clickedGallery");
//Intent intent = new Intent(Intent.ACTION_VIEW, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
Uri uri = null;
Media media = getLatestMedia();
if (media != null) {
uri = media.uri;
}
if (uri != null) {
// check uri exists
if (MyDebug.LOG)
Log.d(TAG, "found most recent uri: " + uri);
try {
ContentResolver cr = getContentResolver();
ParcelFileDescriptor pfd = cr.openFileDescriptor(uri, "r");
if (pfd == null) {
if (MyDebug.LOG)
Log.d(TAG, "uri no longer exists (1): " + uri);
uri = null;
}
pfd.close();
} catch (IOException e) {
if (MyDebug.LOG)
Log.d(TAG, "uri no longer exists (2): " + uri);
uri = null;
}
}
if (uri == null) {
uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
}
if (!is_test) {
// don't do if testing, as unclear how to exit activity to finish test (for testGallery())
if (MyDebug.LOG)
Log.d(TAG, "launch uri:" + uri);
final String REVIEW_ACTION = "com.android.camera.action.REVIEW";
try {
// REVIEW_ACTION means we can view video files without autoplaying
Intent intent = new Intent(REVIEW_ACTION, uri);
this.startActivity(intent);
} catch (ActivityNotFoundException e) {
if (MyDebug.LOG)
Log.d(TAG, "REVIEW_ACTION intent didn't work, try ACTION_VIEW");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
// from http://stackoverflow.com/questions/11073832/no-activity-found-to-handle-intent - needed to fix crash if no gallery app installed
//Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("blah")); // test
if (intent.resolveActivity(getPackageManager()) != null) {
this.startActivity(intent);
} else {
preview.showToast(null, R.string.no_gallery_app);
}
}
}
}
Here is the complete code you can modify the requestCode to whatever you would have declared in your code and you can either pass the Uri or the actual location of the file in the next activity.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_CANCELED) {
if (requestCode == SELECT_FILE && (data != null)) {
Uri selectedImageUri = data.getData();
String[] projection = {MediaStore.MediaColumns.DATA};
Cursor cursor = getContentResolver().query(selectedImageUri, projection, null, null,
null);
assert cursor != null;
int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
cursor.moveToFirst();
String selectedImagePath = cursor.getString(column_index);
if(selectedImagePath == null) {
selectedImagePath = getActualPathFromUri(selectedImageUri);
}
cursor.close();
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
}
private String getActualPathFromUri(Uri selectedImageUri) {
Bitmap bitmap = null;
try {
bitmap = getBitmapFromUri(selectedImageUri);
} catch (IOException e) {
e.printStackTrace();
}
if(bitmap == null) {
return null;
}
File imageFileFolder = new File(getCacheDir(),"appName");
if( !imageFileFolder.exists() ){
imageFileFolder.mkdir();
}
FileOutputStream out = null;
File imageFileName = new File(imageFileFolder, "appName-" + System.currentTimeMillis() + ".jpg");
try {
out = new FileOutputStream(imageFileName);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (IOException e) {
Log.i("Exception", e.getMessage());
} finally {
if(out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return imageFileName.getAbsolutePath();
}
private Bitmap getBitmapFromUri(Uri uri) throws IOException {
ParcelFileDescriptor parcelFileDescriptor =
getContentResolver().openFileDescriptor(uri, "r");
assert parcelFileDescriptor != null;
FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
parcelFileDescriptor.close();
return image;
}
When you back from camera after you take picture or back from gallery your onActivityResult method will call. So override your onActivityResult like the following
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
//Read your image here and set in your imageView
}
}
Edit:
Set image to image view
Inside of the onActivityResult
if(data.getData()==null){
bitmap = (Bitmap)data.getExtras().get("data");
}else{
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), data.getData());
}
yourImageView.setImageBitmap(img);

android KitKat image Crop

I am passing image url to the following method
private void performCrop(Uri imageUri){
try {
Intent intent = new Intent("com.android.camera.action.CROP");
// intent.setType("image/*");
intent.setDataAndType(imageUri, "image/*");
List<ResolveInfo> list = getActivity().getPackageManager().queryIntentActivities( intent, 0 );
int size = list.size();
if (size >= 0) {
intent.setData(imageUri);
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 0);
intent.putExtra("aspectY", 0);
intent.putExtra("outputX", 150);
intent.putExtra("outputY", 150);
intent.putExtra("scale", true);
intent.putExtra("scaleUpIfNeeded", true);
intent.putExtra("return-data", true);
Intent i = new Intent(intent);
ResolveInfo res = list.get(0);
i.setComponent( new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
System.out.println("before startActivityForResult");
try{
startActivityForResult(i, 2);
}catch(Exception e){
e.printStackTrace();
}
}
}
catch(ActivityNotFoundException anfe){
String errorMessage = "Whoops - your device doesn't support the crop action!";
//Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
//toast.show();
}
}
some of images are cropped but some image are not. When I crop image then my app's activity is closed and application starts it's previous or launcher activity so what is the problem??
the main issue is I am not getting any warning or error in log cat, and when I debug it the the till "System.out.println("before startActivityForResult");" the program excutes, that means it does not goes in or calling onActivityResult().
here is onActivityResult method
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if(requestCode ==2 && resultCode == getActivity().RESULT_OK){
System.out.println("inside logic...");
try{
if (data != null) {
// get the returned data
Bundle extras = data.getExtras();
// get the cropped bitmap
Bitmap bmp = extras.getParcelable("data");
imageView.setImageBitmap(bmp);
}
}catch(Exception e){
e.printStackTrace();
}
}
}
this code works successfully for me.try it
private static final int CAMERA_REQUEST = 1;
public static final int MEDIA_TYPE_IMAGE = 1;
final int PIC_CROP = 12;
Button btnCamera;
ImageView iv;
Uri picUri;
static File mediaFile, sendFile;
btnCamera.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
onImgProfile();
}
});
void onImgProfile() {
Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
picUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, picUri);
startActivityForResult(captureIntent, CAMERA_REQUEST);
}
private Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
private File getOutputMediaFile(int type) {
File mediaStorageDir = new File(
Environment.getExternalStorageDirectory(), "MyCameraApp");
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date());
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
} else {
return null;
}
return mediaFile;
}
#SuppressWarnings("unchecked")
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_REQUEST) {
// if (Build.VERSION.SDK_INT < 19) {
try {
if (mediaFile.exists()) {
performCrop();
// new SavePhotoData().execute();
}
} catch (Exception e) {
// TODO: handle exception
}
// }
} else if (requestCode == 11) {
try {
picUri = data.getData();
Log.i("uri", "" + picUri);
performCrop();
} catch (Exception e) {
// TODO: handle exception
}
} else if (requestCode == PIC_CROP) {
// get the returned data
try {
Bundle extras = data.getExtras();
// get the cropped bitmap
Bitmap thePic = extras.getParcelable("data");
// retrieve a reference to the ImageView
// display the returned cropped image
iv.setImageBitmap(thePic);
File mediaStorageDir = new File(
Environment.getExternalStorageDirectory(),
"MyCameraApp");
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("MyCameraApp", "failed to create directory");
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date());
sendFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".png");
FileOutputStream fOut = new FileOutputStream(sendFile);
thePic.compress(Bitmap.CompressFormat.PNG, 85, fOut);
fOut.flush();
fOut.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (resultCode == 3) {
Bundle b = data.getExtras();
b.getString("msg");
}
};
private void performCrop() {
// take care of exceptions
try {
// call the standard crop action intent (the user device may not
// support it)
try {
Intent cropIntent = new Intent("com.android.camera.action.CROP");
// indicate image type and Uri
cropIntent.setDataAndType(picUri, "image/*");
// set crop properties
cropIntent.putExtra("crop", "true");
// indicate aspect of desired crop
cropIntent.putExtra("aspectX", 1);
cropIntent.putExtra("aspectY", 1);
// indicate output X and Y
cropIntent.putExtra("outputX", 256);
cropIntent.putExtra("outputY", 256);
// retrieve data on return
cropIntent.putExtra("return-data", true);
// start the activity - we handle returning in onActivityResult
startActivityForResult(cropIntent, PIC_CROP);
} catch (Exception e) {
// TODO: handle exception
}
}
// respond to users whose devices do not support the crop action
catch (ActivityNotFoundException anfe) {
// display an error message
String errorMessage = "Whoops - your device doesn't support the crop action!";
Toast toast = Toast.makeText(getApplicationContext(), errorMessage,
Toast.LENGTH_SHORT);
toast.show();
}
}
this code works for not only kitkat but all cersion of android
Android all devices does not have a cropping intent according #CommonsWare http://commonsware.com/blog/2013/01/23/no-android-does-not-have-crop-intent.html
so better is to use libraries
some of them are:
https://github.com/jdamcd/android-crop
https://github.com/IsseiAoki/SimpleCropView
https://android-arsenal.com/details/1/3054

Make picture intent failed on Samsung Galaxy I9000

I use the following codes to launch the camera from my app:
private void saveFullImage() {
String storageState = Environment.getExternalStorageState();
if (storageState.equals(Environment.MEDIA_MOUNTED)) {
String path = Environment.getExternalStorageDirectory().getName()
+ File.separatorChar + "Android/data/"
+ RegistrationDetails.this.getPackageName() + "/files/"
+ md5("filedummy") + ".jpg";
File photoFile = new File(path);
try {
if (photoFile.exists() == false) {
photoFile.getParentFile().mkdirs();
photoFile.createNewFile();
}
} catch (IOException e) {
Log.e(TAG, "Could not create file.", e);
}
Log.i(TAG, path);
Uri fileUri = Uri.fromFile(photoFile);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, TAKE_PICTURE);
} else {
new AlertDialog.Builder(this)
.setMessage(
"External Storeage (SD Card) is required.\n\nCurrent state: "
+ storageState).setCancelable(true)
.create().show();
}
}
And I have the following codes in onActivityResult to show that the picture has been taken, so I can proceed the next step:
} else if (requestCode == TAKE_PICTURE) {
if (data == null) {
Toast toast = Toast.makeText(getApplicationContext(),
"Take Picture finished", 10);
toast.show();
}
And I have defined the following settings in AndroidManifest: android.permission.CAMERA and android.permission.WRITE_EXTERNAL_STORAGE
The launch Camera intent works, but when I make a picture and click on Save, then it does not return to onActivityResult and my app crashes.
Can someone help me with this?
Thanks
I got some problems with Galaxy S version 2.3.4 and camera.
After a little work, it actually work with this code (tested with Galaxy S and Nexus S).
You can try it and say me if it works for you.
private Uri mCapturedImageURI;
private void takePhoto() {
String fileName = "temp.jpg";
if (isGalaxyS()) {
fileName = Repertoires_S.getInstance().Get_Photos_Path() + fileName;
File fileTmp = new File(fileName);
if (fileTmp.exists()) fileTmp.delete();
mCapturedImageURI = Uri.fromFile(fileTmp);
} else {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
values.put(MediaStore.Images.Media.DESCRIPTION, "Image prise via XXX :)");
mCapturedImageURI = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
}
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
startActivityForResult(intent, PICK_FROM_CAMERA);
}
private boolean isGalaxyS() {
Log.d("Photo", android.os.Build.BRAND + "/" + android.os.Build.PRODUCT + "/"
+ android.os.Build.DEVICE);
ArrayList<String> devices = new ArrayList<String>();
devices.add("samsung/GT-I9000/GT-I9000");
return devices.contains(android.os.Build.BRAND + "/" + android.os.Build.PRODUCT + "/"
+ android.os.Build.DEVICE);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) {
return;
}
switch (requestCode) {
case PICK_FROM_CAMERA: {
Bitmap photo = null;
String filenameDest = Repertoires_S.getInstance().Get_Photos_Path() + DateTime_BO_S.getInstance().Date_Courante_AAAAMMJJ_HHMMSS() + ".jpg";
File fDest = new File(filenameDest);
String capturedImageFilePath;
if (data == null) {
// "intent.putExtra(MediaStore.EXTRA_OUTPUT, XXXX);" utilisé
try {
if (isGalaxyS()) {
String fileName = "temp.jpg";
capturedImageFilePath = Repertoires_S.getInstance().Get_Photos_Path() + fileName;
} else {
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = managedQuery(mCapturedImageURI, projection, null, null, null);
int column_index_data = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
capturedImageFilePath = cursor.getString(column_index_data);
}
File fSrc = new File(capturedImageFilePath);
fSrc.renameTo(fDest);
photo = BitmapFactory.decodeFile(filenameDest);
} catch (Exception e) {
e.printStackTrace();
}
} else {
// "intent.putExtra(MediaStore.EXTRA_OUTPUT, XXXX);" non utilisé -> miniature
Bundle extras = data.getExtras();
if (extras != null) {
photo = extras.getParcelable("data");
}
}
if (photo != null) {
try {
int tailleMaxPhoto = 800;
double rap;
int newWidth;
int newHeight;
if (photo.getWidth() > tailleMaxPhoto || photo.getHeight() > tailleMaxPhoto) {
// Si c'est plus grand on redimensionne
if (photo.getWidth() > photo.getHeight()) {
rap = (double)tailleMaxPhoto / photo.getWidth();
newWidth = tailleMaxPhoto;
newHeight = (int)((double)photo.getHeight() * rap);
} else {
rap = (double)tailleMaxPhoto / photo.getHeight();
newHeight = tailleMaxPhoto;
newWidth = (int)((double)photo.getWidth() * rap);
}
Bitmap photoSmall = Bitmap.createScaledBitmap(photo, newWidth, newHeight, true);
if (photoSmall != null) {
FileOutputStream out = new FileOutputStream(filenameDest);
if (photoSmall.compress(Bitmap.CompressFormat.JPEG, 90, out)) {
mPhotosPrat.add(filenameDest);
mPhotoAdapt.notifyDataSetChanged();
}
}
} else {
mPhotosPrat.add(filenameDest);
mPhotoAdapt.notifyDataSetChanged();
}
} catch (Exception e) {
e.printStackTrace();
}
}
break;
}
}
}

Categories

Resources