good morning sir, I have used Navigation drawer and fragment. i'm using ActionBarActivity and in which i have called this Fragment. in my Fragment i capture image from camera so in getActivityResult() method not give me Intent values.
public class CameraDemo extends Fragment implements View.OnClickListener {
ImageButton mImgBtnActivityBack,mImgBtnActivityWrong,mImgBtnActivityRight ,mImgBtnActivityEdit ,mImgBtnActivitySearch ,mImgBtnActivityAdd ,mImgBtnActivityNext,mImgBtnActivitySetting;
LinearLayout mLinearLayout1,mLinearLayout2;
Button mFragSignatureClear,mBtnBlack,mBtnRed,mSIBtnSubmit,mSIBtnCamera,mSIBtnAdd ;
PaintView mPaintView;
int currrID = 0;
android.support.v4.app.Fragment fragment;
public int st = 3;
int sizex, sizeh;
Paint paint = new Paint() ;
Uri imageUri=null ;
final int CAMERA_DATA = 1888, INTENT_DATA = 1 ;
Bitmap mbkground ;
public CameraDemo() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
mbkground = null ;
mLinearLayout2=(LinearLayout) rootView.findViewById(R.id.draw);
mPaintView = new PaintView(getActivity().getApplicationContext());
mLinearLayout2.addView(mPaintView);
mFragSignatureClear=(Button) rootView.findViewById(R.id.fragSignatureClear);
mFragSignatureClear.setOnClickListener(this);
mBtnBlack=(Button)rootView.findViewById(R.id.black);
mBtnBlack.setOnClickListener(this);
mBtnRed=(Button)rootView.findViewById(R.id.red);
mBtnRed.setOnClickListener(this);
mSIBtnSubmit=(Button) rootView.findViewById(R.id.fragSIBtnSubmit);
mSIBtnSubmit.setOnClickListener(this);
mSIBtnCamera=(Button) rootView.findViewById(R.id.camera) ;
mSIBtnCamera.setOnClickListener(this) ;
mSIBtnAdd = (Button) rootView.findViewById(R.id.add) ;
mSIBtnAdd . setOnClickListener( this );
DisplayMetrics m = this.getResources().getDisplayMetrics();
float density = getResources().getDisplayMetrics().density;
int w = m.widthPixels;
int h = m.heightPixels;
sizex = w;
sizeh = h;
Log.i("hi", "" + sizex);
Log.i("hi", "" + sizeh);
Log.i("hi", "" + density);
float fsize = sizex / density;
return rootView;
}
#Override
public void onClick(View v) {
if(v.getId()==R.id.black){
currrID=v.getId();
}else if(v.getId()==R.id.black){
currrID=v.getId();
}else if(v.getId()==R.id.fragSIBtnSubmit){
mPaintView.toJPEGFile();
mPaintView.SaveFile();
}else if(v.getId()==R.id.camera){
captureImage();
}else if(v.getId()==R.id.add){
mPaintView.loadFromFile();
}
else {
Toast.makeText(getActivity().getApplicationContext(), "FragSIPhotos Add Button OnClick", Toast.LENGTH_SHORT).show();
}
}
class Point {
float x, y;
public String toString() {
return x + "," + y;
}
}
public class LineData {
List<Point> points = new ArrayList<Point>();
LineData(List<Point> p) {
points.addAll(p);
}
public void Draw(Canvas mCanvas, Paint paint) {
float fData[] = new float[points.size() * 4];
int Index = 0;
for (Point point : points) {
if (Index > 0) {
fData[Index++] = point.x;
fData[Index++] = point.y;
}
fData[Index++] = point.x;
fData[Index++] = point.y;
// canvas.drawCircle(point.x, point.y, 5, paint);
}
if (Index > 2)
mCanvas.drawLines(fData, 0, Index - 2, paint);
}
}
public class PaintView extends View implements View.OnTouchListener {
private static final String TAG = "PaintView" ;
Paint paint = new Paint() ;
int t = 0 ;
List<Point> points = new ArrayList<Point>() ;
List<LineData> pointsred = new ArrayList<LineData>() ;
List<LineData> pointsblack = new ArrayList<LineData>() ;
public PaintView(Context context) {
super(context) ;
setFocusable(true) ;
setFocusableInTouchMode(true) ;
List<Point> points = new ArrayList<Point>() ;
setDrawingCacheEnabled(true) ;
this.setOnTouchListener(this) ;
mbkground = BitmapFactory.decodeResource(getResources(),
R.drawable.plain) ;
paint.setAntiAlias(true) ;
paint.setStrokeMiter(10.0f) ;
paint.setStrokeWidth(st) ;
currrID = R.id.red ;
}
#Override
public void onDraw(Canvas mCanvas) {
mCanvas.drawBitmap(mbkground, 0, 0, null);
// canvas.drawColor(Color.WHITE) ;
this.setBackgroundColor(Color.BLACK);
// To Do Paint for text
//this code for my image app
//yesss very good
/* Paint mText= new Paint(Color.RED);
mText.setTextSize(25);
mCanvas.drawText("Hiren",100,100,mText);
*/ if (currrID == R.id.red)
paint.setColor(Color.RED) ;
else if (currrID == R.id.black)
paint.setColor(Color.BLACK) ;
else
paint.setColor(Color.BLACK) ;
float fdata[] = new float[points.size() * 4] ;
int Index = 0 ;
for (Point point : points) {
if (Index > 0) {
fdata[Index++] = point.x ;
fdata[Index++] = point.y ;
}
fdata[Index++] = point.x ;
fdata[Index++] = point.y ;
// canvas.drawCircle(point.x, point.y, 5, paint);
}
if (Index > 2)
mCanvas.drawLines(fdata, 0, Index - 2, paint);
paint.setColor(Color.RED) ;
for (LineData lines : pointsred)
lines.Draw(mCanvas, paint) ;
paint.setColor(Color.BLACK) ;
for (LineData lines : pointsblack)
lines.Draw(mCanvas, paint) ;
paint.setColor(Color.WHITE) ;
}
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == android.view.MotionEvent.ACTION_DOWN) {
points.clear() ;
} else if (event.getAction() == android.view.MotionEvent.ACTION_UP) {
{
LineData data = new LineData(points) ;
if (currrID == R.id.red)
pointsred.add(data) ;
else if (currrID == R.id.black)
pointsblack.add(data) ;
points.clear() ;
}
} else {
Point point = new Point() ;
point.x = event.getX() ;
point.y = event.getY() ;
points.add(point) ;
}
invalidate() ;
return true;
}
public void toJPEGFile() {
File folder = new File(Environment.getExternalStorageDirectory()
+ "/Mateco/") ;
if (!folder.exists())
folder.mkdirs() ;
try {
this.setDrawingCacheEnabled(true) ;
File f = new File(Environment.getExternalStorageDirectory()
+ "/Mateco/" + "Mateco" + ".png") ;
// file mFile = new File(Environment.g)
FileOutputStream fos = new FileOutputStream(f) ;
Bitmap bitmap = this.getDrawingCache() ;
bitmap.compress(Bitmap.CompressFormat.PNG, 80, fos) ;
// 80 quality bet 0-100 define
fos.flush() ;
fos.close() ;
this.setDrawingCacheEnabled(false) ;
} catch (FileNotFoundException e) {
e.printStackTrace() ;
} catch (IOException e) {
e.printStackTrace() ;
}
}
public void loadFromFile() {
FileInputStream in;
BufferedInputStream buf;
try {
in = new FileInputStream(
Environment.getExternalStorageDirectory() + "/Mateco/"
+ "mateco" + ".jpg");
buf = new BufferedInputStream(in);
mbkground = BitmapFactory.decodeStream(buf);
if (in != null) {
in.close();
}
if (buf != null) {
buf.close();
}
} catch (Exception e) {
Log.e("Error reading file", e.toString());
}
}
public void setBitMap(){
/* mbkground = BitmapFactory.decodeResource(getResources(),
R.drawable.background) ;
*/
}
public void setBitMap(Bitmap photo){
mbkground = photo;
}
public void SaveFile() {
Toast.makeText(getActivity().getApplicationContext(),"Save 1",Toast.LENGTH_SHORT).show();
File folder = new File(Environment.getExternalStorageDirectory()
+ "/Mateco/");
if (!folder.exists())
folder.mkdirs();
try {
this.setDrawingCacheEnabled(true);
t++;
File f = new File(Environment.getExternalStorageDirectory()
+ "/Mateco/" + System.currentTimeMillis() + ".jpg");
FileOutputStream fos = new FileOutputStream(f);
Bitmap bitmap = this.getDrawingCache();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
// 80 quality bet 0-100 define
fos.flush();
fos.close();
File temp = new File(Environment.getExternalStorageDirectory()
+ "/Mateco/" + "Mateco" + ".png");
temp.delete();
this.setDrawingCacheEnabled(false);
} catch (FileNotFoundException e) {
Toast.makeText(getActivity().getApplicationContext(),"FILE_NOT_FOUND_EXCEPTION "+e.getMessage(),Toast.LENGTH_SHORT).show();
e.printStackTrace();
} catch (IOException e) {
Toast.makeText(getActivity().getApplicationContext(),"IO_EXCEPTION "+e.getMessage(),Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
Intent mediaScanIntent = new Intent(
Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(
"file://"
+ Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES));
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
getActivity().getApplicationContext().sendBroadcast(mediaScanIntent);
Toast.makeText(getActivity().getApplicationContext(),"Save 9",Toast.LENGTH_SHORT).show();
} else {
getActivity().getApplicationContext().sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://"
+ Environment.getExternalStorageDirectory())));
Toast.makeText(getActivity().getApplicationContext(),"Save 11",Toast.LENGTH_SHORT).show();
}
}
}
public void captureImage(){
// Define the file-name to save photo taken by Camera activity
String fileName = "Mateco.jpg";
// Create parameters for Intent with filename
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
// Log.e("Intrenal Storage "+MediaStore.Images.Media.INTERNAL_CONTENT_URI.toString(),"");
values.put(MediaStore.Images.Media.DESCRIPTION,"Image capture by camera");
// imageUri is the current activity attribute, define and save it for later usage
Uri imageUri = getActivity().getApplicationContext().getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
/* Uri imageUri=getActivity().getApplicationContext().getContentResolver().insert( MediaStore. Images. Media. INTERNAL_CONTENT_URI,values ) ;
*/
/**** EXTERNAL_CONTENT_URI : style URI for the "primary" external storage volume. ****/
// Standard Intent action that can be sent to have the camera
// application capture an image and return it.
Intent intent = new Intent( MediaStore.ACTION_IMAGE_CAPTURE );
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, INTENT_DATA);
Log.e("captureImage()", "state -1");
getActivity().startActivityForResult(intent, CAMERA_DATA);
Log.e("captureIma ge()", "end");
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.e("OnActivityResult()", "1");
try {
if (requestCode == CAMERA_DATA && resultCode == getActivity().RESULT_OK) {
// Image captured and saved to fileUri specified in the Intent
Log.e("OnActivityResult()", "2");
InputStream stream =getActivity().getApplicationContext(). getContentResolver().openInputStream(
data.getData());
mbkground = BitmapFactory.decodeStream(stream);
Log.e("OnActivityResult()", "2.1");
Bitmap photo = (Bitmap) data.getExtras().get("data");
Log.e("OnActivityResult()", "2.2");
mPaintView.setBitMap(photo);
Log.e("OnActivityResult()", "3");
} else {
// Image capture failed, advise user
Log.e("OnActivityResult()", "5");
}
}catch (Exception objException){
Log.e("onActivityResult();",""+objException.getMessage());
}
}
}
Please change
getActivity().startActivityForResult(intent, CAMERA_DATA);
// this call your activity onActivityResult
to
startActivityForResult(intent, CAMERA_DATA);
// this call your Fragment onActivityResult
And your Activity result like below. super will callback your fragment onActivity resulty
#Override
protected void onActivityResult(int requestId, int responseId, Intent data) {
super.onActivityResult(requestId, responseId, data);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
//to do
}
you should write this method in your activity, not in fragment.
Mr.Lockesh suggesion is right i will apply this and then after only change one variable locally to global solve the problem.
thanks to all
public String getFileName(){
return "file.jpeg" ;
}
public void captureImage(){
// Define the file-name to save photo taken by Camera activity
fileName = getFileName();
Intent mIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
mIntent.putExtra(MediaStore.EXTRA_OUTPUT, getPhotoFileUri(fileName)); // set the image file name
// Start the image capture intent to take photo
startActivityForResult(mIntent, CAMERA_DATA);
}
public Uri getPhotoFileUri(String fileName) {
// Get safe storage directory for photos
File mediaStorageDir = new File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "Camera");
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists() && !mediaStorageDir.mkdirs()){
Log.d("Camera", "failed to create directory");
}
// Return the file target for the photo based on filename
return Uri.fromFile(new File(mediaStorageDir.getPath() + File.separator + fileName));
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_DATA) {
if (resultCode == getActivity().RESULT_OK ) {
Uri takenPhotoUri = getPhotoFileUri(fileName);
// by this point we have the camera photo on disk
Bitmap photo = BitmapFactory.decodeFile(takenPhotoUri.getPath());
// Bitmap photo = (Bitmap) data.getExtras().get("data");
Log.e("OnActivityResult()", "2.2");
mPaintView.setBitMap(photo);
Toast.makeText(getActivity().getApplicationContext(), "Image Set SuccessFully", Toast.LENGTH_SHORT).show();
// Load the taken image into a preview
/* ImageView ivPreview = (ImageView) findViewById(R.id.ivPreview);
ivPreview.setImageBitmap(takenImage);*/
} else { // Result was a failure
Toast.makeText(getActivity().getApplicationContext(), "Picture wasn't taken! or data is null", Toast.LENGTH_SHORT).show();
}
}
}
Related
I am trying to develop some kind of OCR application with Text Recognizing feature. I wrote and found some codes which is working properly but my problem is I want make some customization in the camera layout. I want to add my own capture button and add a frame. I actually did it on a different project with "surface view/holder". But I cannot implement my project because it works so differently.
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_GALLERY = 0;
private static final int REQUEST_CAMERA = 1;
private static final String TAG = MainActivity.class.getSimpleName();
private Uri imageUri;
private TextView detectedTextView; // layouttaki text view
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.choose_from_gallery).setOnClickListener(new View.OnClickListener() { // galeriden resim seçme işlemi
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, REQUEST_GALLERY);
}
});
findViewById(R.id.take_a_photo).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) { // resim çekme işlemi
String filename = System.currentTimeMillis() + ".jpg";
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, filename);
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
imageUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent intent = new Intent();
intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, REQUEST_CAMERA);
}
});
detectedTextView = (TextView) findViewById(R.id.detected_text);
detectedTextView.setMovementMethod(new ScrollingMovementMethod());
}
private void inspectFromBitmap(Bitmap bitmap) { //kendisine gelen bitmap resimden inspect yapar
TextRecognizer textRecognizer = new TextRecognizer.Builder(this).build();
try {
if (!textRecognizer.isOperational()) {
new AlertDialog.
Builder(this).
setMessage("Text recognizer could not be set up on your device").show();
return;
}
Frame frame = new Frame.Builder().setBitmap(bitmap).build();
SparseArray<TextBlock> origTextBlocks = textRecognizer.detect(frame);
List<TextBlock> textBlocks = new ArrayList<>();
for (int i = 0; i < origTextBlocks.size(); i++) {
TextBlock textBlock = origTextBlocks.valueAt(i);
textBlocks.add(textBlock);
}
Collections.sort(textBlocks, new Comparator<TextBlock>() {
#Override
public int compare(TextBlock o1, TextBlock o2) {
int diffOfTops = o1.getBoundingBox().top - o2.getBoundingBox().top;
int diffOfLefts = o1.getBoundingBox().left - o2.getBoundingBox().left;
if (diffOfTops != 0) {
return diffOfTops;
}
return diffOfLefts;
}
});
StringBuilder detectedText = new StringBuilder();
for (TextBlock textBlock : textBlocks) {
if (textBlock != null && textBlock.getValue() != null) {
detectedText.append(textBlock.getValue());
detectedText.append("\n");
}
}
detectedTextView.setText(detectedText); // detectedText is a final string
}
finally {
textRecognizer.release();
}
}
private void inspect(Uri uri) {
InputStream is = null;
Bitmap bitmap = null;
try {
is = getContentResolver().openInputStream(uri);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
options.inSampleSize = 2;
options.inScreenDensity = DisplayMetrics.DENSITY_LOW;
bitmap = BitmapFactory.decodeStream(is, null, options);
Bitmap rotatedMap = RotateBitmap(bitmap,90);
inspectFromBitmap(rotatedMap);
} catch (FileNotFoundException e) {
Log.w(TAG, "Failed to find the file: " + uri, e);
} finally {
if (bitmap != null) {
bitmap.recycle();
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
Log.w(TAG, "Failed to close InputStream", e);
}
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_GALLERY:
if (resultCode == RESULT_OK) {
inspect(data.getData());
}
break;
case REQUEST_CAMERA:
if (resultCode == RESULT_OK) {
if (imageUri != null) {
inspect(imageUri);
}
}
break;
default:
super.onActivityResult(requestCode, resultCode, data);
break;
}
}
public static Bitmap RotateBitmap(Bitmap source, float angle) // it rotates the bitmap for given parameter
{
Matrix matrix = new Matrix();
matrix.postRotate(angle);
return Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, true);
}
In that case, what should I do ? Thank you guys.
No, you cannot change the layout of the camera app that fulfills ACTION_IMAGE_CAPTURE intent. Actually, different devices will not have same camera apps. Each may have very different look-and-feel. You need a 'custom camera' to control its layout and UX.
I am trying to take photo and let the photo saved in portrait orientation. I could not do so even if I changed the manifest nor the intent's orientation to set it portrait. I Google and tried various ways, but none works. Please assist.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.i("request", requestCode + " result " + resultCode + " intent "
+ data);
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == RESULT_SAVE_ITEM){
clearItemContents();
}
else if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK)
{ExifInterface ei = new ExifInterface(cameraImagePath);
int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_UNDEFINED);
switch(orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
rotateImage(bitmap, 90);
break;
case ExifInterface.ORIENTATION_ROTATE_180:
rotateImage(bitmap, 180);
break;
case ExifInterface.ORIENTATION_ROTATE_270:
rotateImage(bitmap, 270);
break;
case ExifInterface.ORIENTATION_NORMAL:
default:
break;
}
openGallery();
}
else{
if (gallery == true) {
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK
&& null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
imageArray = imageToByteArray(new File(picturePath));
setImagePicture(picturePath);
} else {
}
} else if (gallery == false) {
File file = new File(cameraImagePath);
if (file.exists()) {
imageArray = imageToByteArray(file);
setImagePicture(cameraImagePath);
} else {
}
} else {
this.finish();
startActivity(new Intent(this, DefectAdd.class));
}}
}
public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, int pixels)
{
Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap
.getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final int color = 0xff424242;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
final RectF rectF = new RectF(rect);
final float roundPx = pixels;
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
return output;
}
private byte[] imageToByteArray(File file) {
try {
FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
for (int readNum; (readNum = fis.read(buf)) != -1;) {
bos.write(buf, 0, readNum);
System.out.println("read " + readNum + " bytes,");
}
byte[] bytes = bos.toByteArray();
return bytes;
} catch (IOException ex) {
ex.printStackTrace();
}
return null;
}
private void setImagePicture(String photoPath) {
editTextItemPic.setVisibility(ImageView.GONE);
itemImage.setVisibility(ImageView.VISIBLE);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(photoPath, options);
itemImage.setRotation(90);
itemImage.setImageBitmap(bitmap);
}
public void showDialog() {
builder.setTitle("Choose Action!");
builder.setItems(dialogItems, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if (item == 0) {
openGallery();
} else if(item == 1) {
openCamera();
}else{
imageArray = null;
editTextItemPic.setVisibility(ImageView.VISIBLE);
itemImage.setVisibility(ImageView.GONE);
}
}
});
AlertDialog alert = builder.create();
alert.show();
}
public void openGallery() {
MaterialAddActivity.gallery = true;
Intent i = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, MaterialAddActivity.RESULT_LOAD_IMAGE);
}
public void openCamera() {
USE_CAMERA=1;
Intent cameraIntent=new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_SCREEN_ORIENTATION, ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
private String appFolderCheckandCreate() {
String appFolderPath = "";
File externalStorage =Environment.getExternalStorageDirectory();
if (externalStorage.canWrite()) {
appFolderPath = "/storage/emulated/0/DCIM/Camera/";
File dir = new File(externalStorage+"/storage/emulated/0/DCIM/Camera/");
if (!dir.exists()) {
dir.mkdirs();
}
} else {
}
return appFolderPath;
}
#SuppressLint("SimpleDateFormat") private String getTimeStamp() {
final long timestamp = new Date().getTime();
final Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(timestamp);
final String timeString = new SimpleDateFormat("HH_mm_ss_SSS")
.format(cal.getTime());
return timeString;
}
public void saveImage()
{
File filename;
try
{
USE_CAMERA=0;
String path = Environment.getExternalStorageDirectory().toString();
new File(path + "/QSHelper").mkdirs();
filename = new File(path + "/QSHelper/image"+LASTINSERTEDID+".png");
FileOutputStream out = new FileOutputStream(filename);
photo.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
MediaStore.Images.Media.insertImage(getContentResolver(),
filename.getAbsolutePath(), filename.getName(),
filename.getName());
} catch (Exception e)
{
e.printStackTrace();
}
}
Is there any solution to use AQuery library of android for JSON parsing? Do give the code for it. Any solution that makes use of AQuery and no need to create JSONObject instance and to get object from there. Any direct solution for it, please do answer it with a sample of code.
-- Complete code for capturing image ,saving to SD card , pick from gallery,compress,rotate image,etc.. 200% working.
public class A extends AppCompatActivity implements View.OnClickListener, AsyncTaskCompleteListener {
private static final String IMAGE_DIRECTORY = "/idyme";
private static int MAX_IMAGE_DIMENSION = 200;
private final String TAG = "RegisterFragment";
private Button btnVerify, btnUploadImage;
private String ImgPath = null, filePath = null,
profileImageFilePath, profileImageData = null,imageVideoType = "", imageVideoPath = "";
private ImageView ivImage;
private AQuery aQuery;
private Uri uri = null;
private ImageOptions imageOptions;
ActionBar actionBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_vip_registration);
ivImage = (ImageView) findViewById(R.id.ivProfile);
aQuery = new AQuery(this);
imageOptions = new ImageOptions();
imageOptions.memCache = true;
imageOptions.fileCache = true;
imageOptions.fallback = R.drawable.userimage;
}
#Override
public void onClick(View v) {
// onRegisterButtonClick();
switch (v.getId()) {
case R.id.btnUploadImage:
showPictureDialog();
}
}
private void showPictureDialog() {
AlertDialog.Builder pictureDialog = new AlertDialog.Builder(this);
pictureDialog.setTitle(getResources().getString(
R.string.dialog_chhose_photo));
String[] pictureDialogItems = {
getResources().getString(R.string.dialog_from_gallery),
getResources().getString(R.string.dialog_from_camera)};
pictureDialog.setItems(pictureDialogItems,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
choosePhotoFromGallary();
break;
case 1:
takePhotoFromCamera();
break;
}
}
});
pictureDialog.show();
}
private void choosePhotoFromGallary() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, Constants.CHOOSE_PHOTO);
}
private void takePhotoFromCamera() {
Calendar cal = Calendar.getInstance();
File file = new File(Environment.getExternalStorageDirectory(),
(cal.getTimeInMillis() + ".jpg"));
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
} else {
file.delete();
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
// uri = Uri.fromFile(file);
uri = getOutputMediaFileUri();
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
startActivityForResult(cameraIntent, Constants.TAKE_PHOTO);
}
public Uri getOutputMediaFileUri() {
return Uri.fromFile(getOutputMediaFile());
}
private String getRealPathFromURI(Uri contentURI) {
String result;
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = this.getContentResolver().query(contentURI, proj, null, null, null);
if (cursor == null) { // Source is Dropbox or other similar local file
// path
result = contentURI.getPath();
} else {
cursor.moveToFirst();
int idx = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
result = cursor.getString(idx);
cursor.close();
}
return result;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == this.RESULT_CANCELED) {
return;
}
if (requestCode == Constants.CHOOSE_PHOTO) {
if (data != null) {
Uri contentURI = data.getData();
profileImageData = getRealPathFromURI(contentURI);
// new AQuery(getApplicationContext()).id(ivMeme).image(
// profileImageData, imageOptions);
try {
String path = saveImage(scaleImage(this, contentURI));
imageVideoPath = path;
aQuery.id(R.id.ivProfile).image(
imageVideoPath, imageOptions);
} catch (IOException e) {
e.printStackTrace();
Utils.showToast("Failed", this);
}
}
} else if (requestCode == Constants.TAKE_PHOTO) {
// old
if (uri != null) {
profileImageFilePath = uri.getPath();
if (profileImageFilePath != null
&& profileImageFilePath.length() > 0) {
File myFile = new File(profileImageFilePath);
String path = saveImage(BitmapFactory
.decodeFile(profileImageFilePath));
imageVideoPath = path;
aQuery.id(R.id.ivProfile).image(
imageVideoPath, imageOptions);
} else {
Utils.showToast("Failed", this);
}
} else {
Utils.showToast("Failed", this);
}
}
}
public String saveImage(Bitmap myBitmap) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
myBitmap.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File wallpaperDirectory = new File(
Environment.getExternalStorageDirectory() + IMAGE_DIRECTORY);
// have the object build the directory structure, if needed.
if (!wallpaperDirectory.exists()) {
wallpaperDirectory.mkdirs();
}
try {
File 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();
AppLog.Log("TAG", "File Saved::-> " + f.getAbsolutePath());
return f.getAbsolutePath();
} catch (IOException e1) {
e1.printStackTrace();
}
return "";
}
private static File getOutputMediaFile() {
// External sdcard location
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
IMAGE_DIRECTORY);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(IMAGE_DIRECTORY, "Oops! Failed create " + IMAGE_DIRECTORY
+ " directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "VID_" + timeStamp + ".mp4");
return mediaFile;
}
public static Bitmap scaleImage(Context context, Uri photoUri)
throws IOException {
InputStream is = context.getContentResolver().openInputStream(photoUri);
BitmapFactory.Options dbo = new BitmapFactory.Options();
dbo.inJustDecodeBounds = true;
BitmapFactory.decodeStream(is, null, dbo);
is.close();
int rotatedWidth, rotatedHeight;
int orientation = getOrientation(context, photoUri);
if (orientation == 90 || orientation == 270) {
rotatedWidth = dbo.outHeight;
rotatedHeight = dbo.outWidth;
} else {
rotatedWidth = dbo.outWidth;
rotatedHeight = dbo.outHeight;
}
Bitmap srcBitmap;
is = context.getContentResolver().openInputStream(photoUri);
if (rotatedWidth > MAX_IMAGE_DIMENSION
|| rotatedHeight > MAX_IMAGE_DIMENSION) {
float widthRatio = ((float) rotatedWidth)
/ ((float) MAX_IMAGE_DIMENSION);
float heightRatio = ((float) rotatedHeight)
/ ((float) MAX_IMAGE_DIMENSION);
float maxRatio = Math.max(widthRatio, heightRatio);
// Create the bitmap from file
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = (int) maxRatio;
srcBitmap = BitmapFactory.decodeStream(is, null, options);
} else {
srcBitmap = BitmapFactory.decodeStream(is);
}
is.close();
/*
* if the orientation is not 0 (or -1, which means we don't know), we
* have to do a rotation.
*/
if (orientation > 0) {
Matrix matrix = new Matrix();
matrix.postRotate(orientation);
srcBitmap = Bitmap.createBitmap(srcBitmap, 0, 0,
srcBitmap.getWidth(), srcBitmap.getHeight(), matrix, true);
}
String type = context.getContentResolver().getType(photoUri);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (type.equals("image/png")) {
srcBitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
} else if (type.equals("image/jpg") || type.equals("image/jpeg")) {
srcBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
}
byte[] bMapArray = baos.toByteArray();
baos.close();
return BitmapFactory.decodeByteArray(bMapArray, 0, bMapArray.length);
}
public static int getOrientation(Context context, Uri photoUri) {
/* it's on the external media. */
Cursor cursor = context.getContentResolver().query(photoUri,
new String[]{MediaStore.Images.ImageColumns.ORIENTATION},
null, null, null);
if (cursor.getCount() != 1) {
return -1;
}
cursor.moveToFirst();
return cursor.getInt(0);
}
}
--After getting images send it to server , like this :
map.put(Constants.Params.PROFILEPICTURE, imageVideoPath);
// Log.d("image view", profileImageFilePath);
new MultiPartRequester(this, map,
AndyConstants.ServiceCode.VIP_USER_REGISTRATION, this);
-- Permission required :
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
-- dependencies :
compile files('libs/android-query-full.0.26.7.jar')
-- this is full code for json parsing with AQuery library of android
I am working on an Android project in which I have the functionality where user can click on the a button and it will open the camera to upload the image. The upload button is hidden until there is image taken and shown in preview.
What I would like to do is to use the same upload button, which I have set to visible by default now and on clicking it, I would like to open a gallery, which the user can then use to select an image, and it would be shown in preview.
I have a boolean flag to manage this, where if the flag is false, then gallery is opened, else the image in the preview is uploaded.
I have this, but I don't know how to open a gallery and then send the image to preview, to upload. I am new to Android programming, so kindly take that into consideration.
I searched for similar functionality, but the problem is, I have not found, where such features are integrated.
Java code :
RobotoTextView BtnSelectImage;
private ImageView ImgPhoto;
CheckBox profilePhotoCheckBox;
final RestaurantImageServiceImpl restaurantService = new RestaurantImageServiceImpl();
private static final int CAMERA_PHOTO = 111;
private Uri imageToUploadUri;
private static volatile Bitmap reducedSizeBitmap;
ByteArrayOutputStream stream = new ByteArrayOutputStream();
private static boolean galleryFlag = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_restaurant_images);
ImgPhoto = (ImageView) findViewById(R.id.userPhotoImageView);
BtnSelectImage = (RobotoTextView) findViewById(R.id.userPhotoButtonSelect);
profilePhotoCheckBox = (CheckBox)findViewById(R.id.profilePhotoCheckBox);
BtnSelectImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
galleryFlag = true;
captureCameraImage();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Couldn't load photo", Toast.LENGTH_LONG).show();
}
}
});
uploadImageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!(v == null)) {
if(!galleryFlag){
// I think the gallery open code should come here.
}
if (profilePhotoCheckBox.isChecked()) {
uploadImage(true);
}else {
uploadImage(false);
}
new AlertDialog.Builder(AddPhotosForRestaurant.this)
.setTitle("Add more photos")
.setMessage("Are you sure you want to add more photos?")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
startActivity(getIntent());
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(getApplicationContext(), RestaurantMenu.class);
startActivity(intent);
finish();
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
}
});
}
private Bitmap getBitmap(String path) {
Uri uri = Uri.fromFile(new File(path));
InputStream in = null;
try {
final int IMAGE_MAX_SIZE = 1200000; // 1.2MP
in = getContentResolver().openInputStream(uri);
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(in, null, o);
in.close();
int scale = 1;
while ((o.outWidth * o.outHeight) * (1 / Math.pow(scale, 2)) >
IMAGE_MAX_SIZE) {
scale++;
}
Log.d("", "scale = " + scale + ", orig-width: " + o.outWidth + ", orig-height: " + o.outHeight);
Bitmap b = null;
in = getContentResolver().openInputStream(uri);
if (scale > 1) {
scale--;
// scale to max possible inSampleSize that still yields an image
// larger than target
o = new BitmapFactory.Options();
o.inSampleSize = scale;
b = BitmapFactory.decodeStream(in, null, o);
// resize to desired dimensions
int height = b.getHeight();
int width = b.getWidth();
Log.d("", "1th scale operation dimenions - width: " + width + ", height: " + height);
double y = Math.sqrt(IMAGE_MAX_SIZE
/ (((double) width) / height));
double x = (y / height) * width;
Bitmap scaledBitmap = Bitmap.createScaledBitmap(b, (int) x,
(int) y, true);
b.recycle();
b = scaledBitmap;
System.gc();
} else {
b = BitmapFactory.decodeStream(in);
}
in.close();
Log.d("", "bitmap size - width: " + b.getWidth() + ", height: " +
b.getHeight());
return b;
} catch (IOException e) {
Log.e("", e.getMessage(), e);
return null;
}
}
private void captureCameraImage() {
Intent chooserIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(Environment.getExternalStorageDirectory(), "POST_IMAGE.jpg");
chooserIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
imageToUploadUri = Uri.fromFile(f);
startActivityForResult(chooserIntent, CAMERA_PHOTO);
}
#Override
public void onBackPressed() {
Intent intent = new Intent(this, Login.class);
StaticRestTemplate.setReplyString("");
StaticRestTemplate.setLoggedInUser("");
StaticRestTemplate.setJsessionid("");
startActivity(intent);
finish();
}
#Override
protected void onActivityResult(final int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_PHOTO && resultCode == Activity.RESULT_OK) {
if(imageToUploadUri != null){
Uri selectedImage = imageToUploadUri;
getContentResolver().notifyChange(selectedImage, null);
reducedSizeBitmap = getBitmap(imageToUploadUri.getPath());
if(reducedSizeBitmap != null){
ImgPhoto.setImageBitmap(reducedSizeBitmap);
RobotoTextView uploadImageButton = (RobotoTextView) findViewById(R.id.uploadUserImageButton);
uploadImageButton.setVisibility(View.VISIBLE);
}else{
Toast.makeText(this,"Error while capturing Image",Toast.LENGTH_LONG).show();
}
}else{
Toast.makeText(this,"Error while capturing Image",Toast.LENGTH_LONG).show();
}
}
}
private void uploadImage(boolean profilePhoto) {
if(!(reducedSizeBitmap == null)){
if(reducedSizeBitmap == null){
Log.d("Image bitmap"," Is null");
}
reducedSizeBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
this.restaurantService.addRestaurantImage(byteArray,profilePhoto);
}
}
}
I hope this much information is enough. Can anyone point me which functions I should put and where. Thanks a lot. :-)
Edit with Answer
Finally the integration works. I had to combine answers from the one I received and here on SO.
Final Code
public class AddPhotosForRestaurant extends RestaurantDrawerActivity {
RobotoTextView BtnSelectImage;
private ImageView ImgPhoto;
CheckBox profilePhotoCheckBox;
final RestaurantImageServiceImpl restaurantService = new RestaurantImageServiceImpl();
private static final int CAMERA_PHOTO = 111;
public static final int GALLERY_INTENT_REQUEST_CODE = 0x000005;
private Uri imageToUploadUri = null;
private static volatile Bitmap reducedSizeBitmap;
ByteArrayOutputStream stream = new ByteArrayOutputStream();
private boolean galleryFlag = false;
private boolean uploadNow = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_restaurant_images);
set(null, null);
final RobotoTextView uploadImageButton = (RobotoTextView) findViewById(R.id.uploadUserImageButton);
ImgPhoto = (ImageView) findViewById(R.id.userPhotoImageView);
BtnSelectImage = (RobotoTextView) findViewById(R.id.userPhotoButtonSelect);
profilePhotoCheckBox = (CheckBox) findViewById(R.id.profilePhotoCheckBox);
BtnSelectImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
galleryFlag = true;
captureCameraImage();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Couldn't load photo", Toast.LENGTH_LONG).show();
}
}
});
uploadImageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!(v == null)) {
if (uploadNow) {
uploadNow = false;
galleryFlag = true;
if (profilePhotoCheckBox.isChecked()) {
uploadImage(true);
} else {
uploadImage(false);
}
}
if (!galleryFlag) {
galleryFlag = true;
uploadNow = true;
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"),
GALLERY_INTENT_REQUEST_CODE);
} else {
if (profilePhotoCheckBox.isChecked()) {
uploadImage(true);
} else {
uploadImage(false);
}
new AlertDialog.Builder(AddPhotosForRestaurant.this)
.setTitle("Add more photos")
.setMessage("Are you sure you want to add more photos?")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
startActivity(getIntent());
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(getApplicationContext(), RestaurantMenu.class);
startActivity(intent);
finish();
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
}
}
});
}
private Bitmap getBitmap(String path) {
Uri uri = Uri.fromFile(new File(path));
InputStream in = null;
try {
final int IMAGE_MAX_SIZE = 1200000; // 1.2MP
in = getContentResolver().openInputStream(uri);
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(in, null, o);
in.close();
int scale = 1;
while ((o.outWidth * o.outHeight) * (1 / Math.pow(scale, 2)) >
IMAGE_MAX_SIZE) {
scale++;
}
Bitmap b;
in = getContentResolver().openInputStream(uri);
if (scale > 1) {
scale--;
// scale to max possible inSampleSize that still yields an image
// larger than target
o = new BitmapFactory.Options();
o.inSampleSize = scale;
b = BitmapFactory.decodeStream(in, null, o);
// resize to desired dimensions
int height = b.getHeight();
int width = b.getWidth();
double y = Math.sqrt(IMAGE_MAX_SIZE
/ (((double) width) / height));
double x = (y / height) * width;
Bitmap scaledBitmap = Bitmap.createScaledBitmap(b, (int) x,
(int) y, true);
b.recycle();
b = scaledBitmap;
System.gc();
} else {
b = BitmapFactory.decodeStream(in);
}
in.close();
return b;
} catch (IOException e) {
return null;
}
}
private void captureCameraImage() {
Intent chooserIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(Environment.getExternalStorageDirectory(), "POST_IMAGE.jpg");
chooserIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
imageToUploadUri = Uri.fromFile(f);
startActivityForResult(chooserIntent, CAMERA_PHOTO);
}
#Override
public void onBackPressed() {
Intent intent = new Intent(this, Login.class);
StaticRestTemplate.setReplyString("");
StaticRestTemplate.setLoggedInUser("");
StaticRestTemplate.setJsessionid("");
startActivity(intent);
finish();
}
#Override
protected void onActivityResult(final int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_PHOTO && resultCode == Activity.RESULT_OK) {
if (imageToUploadUri != null) {
Uri selectedImage = imageToUploadUri;
getContentResolver().notifyChange(selectedImage, null);
reducedSizeBitmap = getBitmap(imageToUploadUri.getPath());
if (reducedSizeBitmap != null) {
ImgPhoto.setImageBitmap(reducedSizeBitmap);
RobotoTextView uploadImageButton = (RobotoTextView) findViewById(R.id.uploadUserImageButton);
uploadImageButton.setVisibility(View.VISIBLE);
} else {
Toast.makeText(this, "Error while capturing Image", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(this, "Error while capturing Image", Toast.LENGTH_LONG).show();
}
}
if (requestCode == GALLERY_INTENT_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
try {
Uri selectedImage = Uri.parse(data.getDataString());
reducedSizeBitmap = MediaStore.Images.Media.getBitmap(
getApplicationContext().getContentResolver(),
selectedImage);
ImgPhoto.setImageBitmap(reducedSizeBitmap);
} catch (Exception e) {
Toast.makeText(this, "Error while selecting Image", Toast.LENGTH_LONG).show();
}
}
}
private void uploadImage(boolean profilePhoto) {
if (!(reducedSizeBitmap == null)) {
reducedSizeBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
this.restaurantService.addRestaurantImage(byteArray, profilePhoto);
}
}
}
Thanks a lot for all your help.. :-)
In Constant file write in my case(ActivityConstantUtils.java)
public static final int GALLERY_INTENT_REQUEST_CODE = 0x000005;
To open Gallery & get path of selected image use following code :
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
photoPickerIntent.setType("image/*");
photoPickerIntent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
mActPanelFragment.startActivityForResult(photoPickerIntent, ActivityConstantUtils.GALLERY_INTENT_REQUEST_CODE);
After that you get path in onActivityResult() method
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
(requestCode == ActivityConstantUtils.GALLERY_INTENT_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
try {
String imagePath = getFilePath(data);
// TODO: Here you set data to preview screen
}catch(Exception e){}
}
}
private String getFilePath(Intent data) {
String imagePath;
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getActivity().getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imagePath = cursor.getString(columnIndex);
cursor.close();
return imagePath;
}
I have an image view in android and on that image view i have another image view.. Both image views contain two different images.. Now i want to save it as a single JPG image in my phone gallery.. So how can i do that??
I tried some code but it is not working.
Here is my code.
XML File:
<ImageView
android:id="#+id/innerImage"
android:layout_width="300dp"
android:layout_height="230dp"
android:layout_centerInParent="true"
android:layout_centerVertical="true"
android:contentDescription="#android:string/untitled"
android:background="#drawable/white"/>
<Button
android:id="#+id/btnselectPhoto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/ivImage"
android:layout_alignLeft="#+id/ivImage"
android:layout_marginBottom="16dp"
android:text="#string/select_photo" />
<ImageView
android:id="#+id/ivImage"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:contentDescription="#android:string/untitled" />
<Button
android:id="#+id/btnsave"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#id/btnselectPhoto"
android:layout_alignBottom="#id/btnselectPhoto"
android:layout_alignRight="#+id/ivImage"
android:layout_marginLeft="32dp"
android:layout_toRightOf="#id/btnselectPhoto"
android:text="#string/save" />
And here is my Java Code:
public class MainActivity extends ActionBarActivity {
private static String mTempDir;
Bitmap mBackImage, mTopImage, mBackground, mNewSaving;
Canvas mComboImage;
FileOutputStream mFileOutputStream;
BitmapDrawable mBitmapDrawable;
private String mCurrent = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Call method for selecting Image
SelectImage();
}
// method for selecting image
private void SelectImage() {
// items to put in alert box
final CharSequence[] items = { "Take Photo", "Choose from Library", "Cancel" };
// Alert box
final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Add Photo");
// Click Event of button
Button btn = (Button) findViewById(R.id.btnselectPhoto);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Set items in alert box
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
// Start Camara
if (items[item].equals("Take Photo")) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(intent, 1);
}
// Open Gallery
else if (items[item].equals("Choose from Library")) {
Intent intent = new Itent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(intent, 2);
}
// Cancel code
else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
});
}
// This method is called for setting image in imageview.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
final String picturePath;
ImageView iv = (ImageView) findViewById(R.id.innerImage);
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
File f = new File(Environment.getExternalStorageDirectory().toString());
for (File temp : f.listFiles()) {
if (temp.getName().equals("temp.jpg")) {
f = temp;
break;
}
}
try {
Bitmap bm;
BitmapFactory.Options btmapOptions = new BitmapFactory.Options();
bm = BitmapFactory.decodeFile(f.getAbsolutePath(), btmapOptions);
// bm = Bitmap.createScaledBitmap(bm, 70, 70, true);
iv.setImageBitmap(bm);
String path = android.os.Environment.getExternalStorageDirectory() + File.separator + "Phoenix" + File.separator + "default";
f.delete();
OutputStream fOut = null;
File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
try {
fOut = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.JPEG, 85, fOut);
fOut.flush();
fOut.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
}
catch (Exception e) {
e.printStackTrace();
}
}
else if (requestCode == 2) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
picturePath = cursor.getString(columnIndex);
cursor.close();
// Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
iv.setImageBitmap(BitmapFactory.decodeFile(picturePath));
saveimage(picturePath);
}
}
}
private void saveimage(String imgPath) {
mTempDir = Environment.getExternalStorageDirectory() + "/" + "Demo" + "/";
File mTempFile = new File(mTempDir);
if (!mTempFile.exists()) {
mTempFile.mkdirs();
}
mCurrent = "temp.png";
mBackground = Bitmap.createBitmap(604, 1024, Bitmap.Config.ARGB_8888);
mBackImage = BitmapFactory.decodeResource(getResources(), R.drawable.image1);
mTopImage = BitmapFactory.decodeFile(imgPath);
mComboImage = new Canvas(mBackground);
mComboImage.drawBitmap(mBackImage, 0f, 0f, null);
mComboImage.drawBitmap(mTopImage, 0f, 0f, null);
Button savebtn = (Button) findViewById(R.id.btnsave);
savebtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
try {
mBitmapDrawable = new BitmapDrawable(getResources(), mBackground);
mNewSaving = ((BitmapDrawable) mBitmapDrawable).getBitmap();
String FtoSave = mTempDir + mCurrent;
File mFile = new File(FtoSave);
mFileOutputStream = new FileOutputStream(mFile);
mNewSaving.compress(CompressFormat.PNG, 95, mFileOutputStream);
mFileOutputStream.flush();
mFileOutputStream.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
I worked on a similar issue once, and i solved it by putting both images in the same linear layout an creating Bitmap from that layout. Than you can just write a function to save that Bitmap where ever you want.
Here's some sample code:
private Bitmap getBitmap(View v) {
v.clearFocus();
v.setPressed(false);
boolean willNotCache = v.willNotCacheDrawing();
v.setWillNotCacheDrawing(false);
// Reset the drawing cache background color to fully transparent
// for the duration of this operation
int color = v.getDrawingCacheBackgroundColor();
v.setDrawingCacheBackgroundColor(0);
if (color != 0) {
v.destroyDrawingCache();
}
v.buildDrawingCache();
Bitmap cacheBitmap = v.getDrawingCache();
if (cacheBitmap == null) {
Toast.makeText(StopWarApp.getContext(), "Something went wrong",
Toast.LENGTH_SHORT).show();
return null;
}
Bitmap bitmap = Bitmap.createBitmap(cacheBitmap);
// Restore the view
v.destroyDrawingCache();
v.setWillNotCacheDrawing(willNotCache);
v.setDrawingCacheBackgroundColor(color);
return bitmap;
}
public void combineImages(Bitmap c, Bitmap s,String loc) {
Bitmap cs = null;
int width, height = 0;
if(c.getWidth() > s.getWidth()) {
width = c.getWidth();
height = c.getHeight() + s.getHeight();
} else {
width = s.getWidth();
height = c.getHeight() + s.getHeight();
}
cs = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas comboImage = new Canvas(cs);
comboImage.drawBitmap(c, 0f, 0f, null);
comboImage.drawBitmap(s, 0f, c.getHeight(), null);
String tmpImg = String.valueOf(System.currentTimeMillis()) + ".png";
OutputStream os = null;
try {
os = new FileOutputStream(loc + tmpImg);
cs.compress(CompressFormat.PNG, 100, os);
} catch(IOException e) {
Log.e("combineImages", "problem combining images", e);
}
}
You can combine two bitmaps using this.
LinearLayout ll;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.layout2);
ll=(LinearLayout)findViewById(R.id.linearlayout);
//Add button in your layout and write the below code onclick of button.
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
ll.setDrawingCacheEnabled(true);
Bitmap bitmap = ll.getDrawingCache();
String root = Environment.getExternalStorageDirectory().toString();
File newDir = new File(root + "/saved_picture");
newDir.mkdirs();
Random gen = new Random();
int n = 10000;
n = gen.nextInt(n);
String fotoname = n + ".jpg";
File file = new File(newDir, fotoname);
String s = file.getAbsolutePath();
System.err.print("Path of saved image." + s);
try {
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
}
}
});