Azure Cognitive Services Face Android - NoClassDefFoundError - android

I am trying to make an app to detect face using Face API from Azure's tutorial. When I try to run the app, I get an Error:
java.lang.NoClassDefFoundError: Failed resolution of: Lorg/apache/http/impl/client/DefaultHttpClient;
at com.microsoft.projectoxford.face.rest.WebServiceRequest.(WebServiceRequest.java:67)
at com.microsoft.projectoxford.face.FaceServiceRestClient.(FaceServiceRestClient.java:99)
at com.contoso.facetutorial.MainActivity.(MainActivity.java:28)
Here is my code:
MainActivity.java
package com.contoso.facetutorial;
// <snippet_imports>
import java.io.*;
import java.lang.Object.*;
import android.app.*;
import android.content.*;
import android.net.*;
import android.os.*;
import android.view.*;
import android.graphics.*;
import android.widget.*;
import android.provider.*;
// </snippet_imports>
// <snippet_face_imports>
import com.microsoft.projectoxford.face.*;
import com.microsoft.projectoxford.face.contract.*;
// </snippet_face_imports>
public class MainActivity extends Activity {
// <snippet_mainactivity_fields>
// Add your Face endpoint to your environment variables.
private final String apiEndpoint = "https://ceranfaceapi.cognitiveservices.azure.com/";
// Add your Face subscription key to your environment variables.
private final String subscriptionKey = "xxxx";
private final FaceServiceClient faceServiceClient =
new FaceServiceRestClient(apiEndpoint, subscriptionKey);
private final int PICK_IMAGE = 1;
private ProgressDialog detectionProgressDialog;
// </snippet_mainactivity_fields>
// <snippet_mainactivity_methods>
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button1 = findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(
intent, "Select Picture"), PICK_IMAGE);
}
});
detectionProgressDialog = new ProgressDialog(this);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE && resultCode == RESULT_OK &&
data != null && data.getData() != null) {
Uri uri = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(
getContentResolver(), uri);
ImageView imageView = findViewById(R.id.imageView1);
imageView.setImageBitmap(bitmap);
// Comment out for tutorial
detectAndFrame(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
// </snippet_mainactivity_methods>
}
// <snippet_detection_methods>
// Detect faces by uploading a face image.
// Frame faces after detection.
private void detectAndFrame(final Bitmap imageBitmap) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
ByteArrayInputStream inputStream =
new ByteArrayInputStream(outputStream.toByteArray());
AsyncTask<InputStream, String, Face[]> detectTask =
new AsyncTask<InputStream, String, Face[]>() {
String exceptionMessage = "";
#Override
protected Face[] doInBackground(InputStream... params) {
try {
publishProgress("Detecting...");
Face[] result = faceServiceClient.detect(
params[0],
true, // returnFaceId
false, // returnFaceLandmarks
null // returnFaceAttributes:
/* new FaceServiceClient.FaceAttributeType[] {
FaceServiceClient.FaceAttributeType.Age,
FaceServiceClient.FaceAttributeType.Gender }
*/
);
if (result == null){
publishProgress(
"Detection Finished. Nothing detected");
return null;
}
publishProgress(String.format(
"Detection Finished. %d face(s) detected",
result.length));
return result;
} catch (Exception e) {
exceptionMessage = String.format(
"Detection failed: %s", e.getMessage());
return null;
}
}
#Override
protected void onPreExecute() {
//TODO: show progress dialog
detectionProgressDialog.show();
}
#Override
protected void onProgressUpdate(String... progress) {
//TODO: update progress
detectionProgressDialog.setMessage(progress[0]);
}
#Override
protected void onPostExecute(Face[] result) {
//TODO: update face frames
detectionProgressDialog.dismiss();
if(!exceptionMessage.equals("")){
showError(exceptionMessage);
}
if (result == null) return;
ImageView imageView = findViewById(R.id.imageView1);
imageView.setImageBitmap(
drawFaceRectanglesOnBitmap(imageBitmap, result));
imageBitmap.recycle();
}
};
detectTask.execute(inputStream);
}
private void showError(String message) {
new AlertDialog.Builder(this)
.setTitle("Error")
.setMessage(message)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}})
.create().show();
}
// </snippet_detection_methods>
// <snippet_drawrectangles>
private static Bitmap drawFaceRectanglesOnBitmap(
Bitmap originalBitmap, Face[] faces) {
Bitmap bitmap = originalBitmap.copy(Bitmap.Config.ARGB_8888, true);
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setStyle(Paint.Style.STROKE);
paint.setColor(Color.RED);
paint.setStrokeWidth(10);
if (faces != null) {
for (Face face : faces) {
FaceRectangle faceRectangle = face.faceRectangle;
canvas.drawRect(
faceRectangle.left,
faceRectangle.top,
faceRectangle.left + faceRectangle.width,
faceRectangle.top + faceRectangle.height,
paint);
}
}
return bitmap;
}
// </snippet_drawrectangles>
}

To continue using the Apache HTTP client, apps that target Android 9 and above can add the following to their AndroidManifest.xml:
<uses-library android:name="org.apache.http.legacy" android:required="false"/>

Related

Android MediaProjection permission dialog visibility callback

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.PixelFormat;
import android.graphics.Point;
import android.hardware.display.DisplayManager;
import android.hardware.display.VirtualDisplay;
import android.media.Image;
import android.media.ImageReader;
import android.media.projection.MediaProjection;
import android.media.projection.MediaProjectionManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.OrientationEventListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
public class ScreenCaptureImageActivity extends Activity {
private static final String TAG = ScreenCaptureImageActivity.class.getName();
private static final int REQUEST_CODE = 100;
private static String STORE_DIRECTORY;
private static int IMAGES_PRODUCED;
private static final String SCREENCAP_NAME = "screencap";
private static final int VIRTUAL_DISPLAY_FLAGS = DisplayManager.VIRTUAL_DISPLAY_FLAG_OWN_CONTENT_ONLY | DisplayManager.VIRTUAL_DISPLAY_FLAG_PUBLIC;
private static MediaProjection sMediaProjection;
private MediaProjectionManager mProjectionManager;
private ImageReader mImageReader;
private Handler mHandler;
private Display mDisplay;
private VirtualDisplay mVirtualDisplay;
private int mDensity;
private int mWidth;
private int mHeight;
private int mRotation;
private OrientationChangeCallback mOrientationChangeCallback;
private class ImageAvailableListener implements ImageReader.OnImageAvailableListener {
#Override
public void onImageAvailable(ImageReader reader) {
Image image = null;
FileOutputStream fos = null;
Bitmap bitmap = null;
try {
image = reader.acquireLatestImage();
if (image != null) {
Image.Plane[] planes = image.getPlanes();
ByteBuffer buffer = planes[0].getBuffer();
int pixelStride = planes[0].getPixelStride();
int rowStride = planes[0].getRowStride();
int rowPadding = rowStride - pixelStride * mWidth;
// create bitmap
bitmap = Bitmap.createBitmap(mWidth + rowPadding / pixelStride, mHeight, Bitmap.Config.ARGB_8888);
bitmap.copyPixelsFromBuffer(buffer);
// write bitmap to a file
fos = new FileOutputStream(STORE_DIRECTORY + "/myscreen_" + IMAGES_PRODUCED + ".png");
bitmap.compress(CompressFormat.JPEG, 100, fos);
IMAGES_PRODUCED++;
Log.e(TAG, "captured image: " + IMAGES_PRODUCED);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
if (bitmap != null) {
bitmap.recycle();
}
if (image != null) {
image.close();
}
}
}
}
private class OrientationChangeCallback extends OrientationEventListener {
OrientationChangeCallback(Context context) {
super(context);
}
#Override
public void onOrientationChanged(int orientation) {
final int rotation = mDisplay.getRotation();
if (rotation != mRotation) {
mRotation = rotation;
try {
// clean up
if (mVirtualDisplay != null) mVirtualDisplay.release();
if (mImageReader != null) mImageReader.setOnImageAvailableListener(null, null);
// re-create virtual display depending on device width / height
createVirtualDisplay();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
private class MediaProjectionStopCallback extends MediaProjection.Callback {
#Override
public void onStop() {
Log.e("ScreenCapture", "stopping projection.");
mHandler.post(new Runnable() {
#Override
public void run() {
if (mVirtualDisplay != null) mVirtualDisplay.release();
if (mImageReader != null) mImageReader.setOnImageAvailableListener(null, null);
if (mOrientationChangeCallback != null) mOrientationChangeCallback.disable();
sMediaProjection.unregisterCallback(MediaProjectionStopCallback.this);
}
});
}
}
/****************************************** Activity Lifecycle methods ************************/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// call for the projection manager
mProjectionManager = (MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE);
// start projection
Button startButton = (Button) findViewById(R.id.startButton);
startButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
startProjection();
}
});
// stop projection
Button stopButton = (Button) findViewById(R.id.stopButton);
stopButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
stopProjection();
}
});
// start capture handling thread
new Thread() {
#Override
public void run() {
Looper.prepare();
mHandler = new Handler();
Looper.loop();
}
}.start();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE) {
sMediaProjection = mProjectionManager.getMediaProjection(resultCode, data);
if (sMediaProjection != null) {
File externalFilesDir = getExternalFilesDir(null);
if (externalFilesDir != null) {
STORE_DIRECTORY = externalFilesDir.getAbsolutePath() + "/screenshots/";
File storeDirectory = new File(STORE_DIRECTORY);
if (!storeDirectory.exists()) {
boolean success = storeDirectory.mkdirs();
if (!success) {
Log.e(TAG, "failed to create file storage directory.");
return;
}
}
} else {
Log.e(TAG, "failed to create file storage directory, getExternalFilesDir is null.");
return;
}
// display metrics
DisplayMetrics metrics = getResources().getDisplayMetrics();
mDensity = metrics.densityDpi;
mDisplay = getWindowManager().getDefaultDisplay();
// create virtual display depending on device width / height
createVirtualDisplay();
// register orientation change callback
mOrientationChangeCallback = new OrientationChangeCallback(this);
if (mOrientationChangeCallback.canDetectOrientation()) {
mOrientationChangeCallback.enable();
}
// register media projection stop callback
sMediaProjection.registerCallback(new MediaProjectionStopCallback(), mHandler);
}
}
}
/****************************************** UI Widget Callbacks *******************************/
private void startProjection() {
startActivityForResult(mProjectionManager.createScreenCaptureIntent(), REQUEST_CODE);
}
private void stopProjection() {
mHandler.post(new Runnable() {
#Override
public void run() {
if (sMediaProjection != null) {
sMediaProjection.stop();
}
}
});
}
/****************************************** Factoring Virtual Display creation ****************/
private void createVirtualDisplay() {
// get width and height
Point size = new Point();
mDisplay.getSize(size);
mWidth = size.x;
mHeight = size.y;
// start capture reader
mImageReader = ImageReader.newInstance(mWidth, mHeight, PixelFormat.RGBA_8888, 2);
mVirtualDisplay = sMediaProjection.createVirtualDisplay(SCREENCAP_NAME, mWidth, mHeight, mDensity, VIRTUAL_DISPLAY_FLAGS, mImageReader.getSurface(), null, mHandler);
mImageReader.setOnImageAvailableListener(new ImageAvailableListener(), mHandler);
}
}
Beginning with startButton.onclick() a system? permission dialog is shown as a result of calling startActivityForResult(mProjectionManager.createScreenCaptureIntent(), REQUEST_CODE);.
Then, the user either accept or decline the permission request. Therefore closing the permission dialog.
After that, we receive a callback of this action onActivityResult() with the REQUEST_CODE. We could use this opportunity to call something, but this is not really helpful since our goal is to fetch the first image that is clear of the dialog. After the callback, the dialog is starting to fade.
Now, if the permission was granted, dirty Image(s) now start being dispatched to the now registered ImageAvailableListener.onImageAvailable(...).
We receive an Image immediately after the user accepted. But the first few frames, after the callback, are dirty by showing a fading permission dialog. Is there a way to get a reference of this permission dialog so that we know exactly when it is no longer visible on screen?
A quick hack would be to add a delay to allow for the dialog box to disappear. Or skip the few dirty frames to get the first clean image...
full code: https://github.com/mtsahakis/MediaProjectionDemo

passing byte Array image into next Activity

My app consist Image Capture Face Recognition what i need to implement is converting the byte Array image into bitmap , and pass the bitmap to next Activity, The next Activity will receive the bitmap and show it in an image-view , than convert the bitmap into base 64.
I Don't know how to implement above task into my existing codes.
So when image is captured it shows, once click to save button pass the image to next activity and again convert the bitmap into base64.
FaceTrackerAcivity.java
public final class FaceTrackerActivity extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = "FaceTracker";
private CameraSource mCameraSource = null;
private CameraSourcePreview mPreview;
private GraphicOverlay mGraphicOverlay;
private ImageView btnCapture;
private ImageView btnChangeCamera;
private ImageView btnCancel;
private ImageView btnSave;
private FrameLayout frmResult;
private ImageView imgPicture;
Bitmap bmp;
private static final int RC_HANDLE_GMS = 9001;
// permission request codes need to be < 256
private static final int RC_HANDLE_CAMERA_PERM = 2;
private static final int RC_HANDLE_WRITE_EXTERNAL_STORAGE_PERM = 3;
private int cameraId = CameraSource.CAMERA_FACING_BACK;
Intent x;
//==============================================================================================
// Activity Methods
//==============================================================================================
/**
* Initializes the UI and initiates the creation of a face detector.
*/
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
mPreview = (CameraSourcePreview) findViewById(R.id.preview);
mGraphicOverlay = (GraphicOverlay) findViewById(R.id.faceOverlay);
btnCapture = (ImageView) findViewById(R.id.btn_capture);
btnChangeCamera = (ImageView) findViewById(R.id.btn_change_camera);
btnCancel = (ImageView) findViewById(R.id.btn_cancel);
btnSave = (ImageView) findViewById(R.id.btn_save);
frmResult = (FrameLayout) findViewById(R.id.frm_capture_result);
imgPicture = (ImageView) findViewById(R.id.img_capture_result);
boolean hasPermissionCamera = (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED);
if (!hasPermissionCamera) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, RC_HANDLE_CAMERA_PERM);
} else {
boolean hasPermissionWriteStorage = (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED);
if (!hasPermissionWriteStorage) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, RC_HANDLE_WRITE_EXTERNAL_STORAGE_PERM);
} else {
createCameraSource(cameraId);
}
}
btnCapture.setOnClickListener(this);
btnChangeCamera.setOnClickListener(this);
}
private void createCameraSource(int cameraId) {
Context context = getApplicationContext();
FaceDetector detector = new FaceDetector.Builder(context)
.setClassificationType(FaceDetector.ALL_CLASSIFICATIONS)
.build();
detector.setProcessor(
new MultiProcessor.Builder<>(new GraphicFaceTrackerFactory())
.build());
if (!detector.isOperational()) {
Log.w(TAG, "Face detector dependencies are not yet available.");
}
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
mCameraSource = new CameraSource.Builder(context, detector)
.setRequestedPreviewSize(metrics.heightPixels, metrics.widthPixels)
.setFacing(cameraId)
.setAutoFocusEnabled(true)
.setRequestedFps(30.0f)
.build();
}
#Override
protected void onResume() {
super.onResume();
startCameraSource();
}
#Override
protected void onPause() {
super.onPause();
mPreview.stop();
}
#Override
protected void onDestroy() {
super.onDestroy();
if (mCameraSource != null) {
mCameraSource.release();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case RC_HANDLE_CAMERA_PERM: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
finish();
startActivity(getIntent());
}
break;
}
case RC_HANDLE_WRITE_EXTERNAL_STORAGE_PERM: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
finish();
startActivity(getIntent());
}
break;
}
}
}
private void startCameraSource() {
// check that the device has play services available.
int code = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(
getApplicationContext());
if (code != ConnectionResult.SUCCESS) {
Dialog dlg = GoogleApiAvailability.getInstance().getErrorDialog(this, code, RC_HANDLE_GMS);
dlg.show();
}
if (mCameraSource != null) {
try {
mPreview.start(mCameraSource, mGraphicOverlay);
} catch (IOException e) {
Log.e(TAG, "Unable to start camera source.", e);
mCameraSource.release();
mCameraSource = null;
}
}
}
#Override
public void onClick(View v) {
int id = v.getId();
if (id == R.id.btn_capture) {
Toast.makeText(this, "capture", Toast.LENGTH_SHORT).show();
mCameraSource.takePicture(null, new CameraSource.PictureCallback() {
#Override
public void onPictureTaken(final byte[] bytes) {
int orientation = Exif.getOrientation(bytes);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2;
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length, options);
switch (orientation) {
case 90:
bmp = Utils.rotateImage(bmp, 90);
break;
case 180:
bmp = Utils.rotateImage(bmp, 180);
break;
case 270:
bmp = Utils.rotateImage(bmp, 270);
break;
}
if (cameraId == CameraSource.CAMERA_FACING_FRONT) {
bmp = Utils.flip(bmp, Constants.FLIP_HORIZONTAL);
}
if (bmp != null) {
frmResult.setVisibility(View.VISIBLE);
imgPicture.setImageBitmap(bmp);
btnCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
frmResult.setVisibility(View.GONE);
}
});
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SavePhotoTask savePhotoTask = new SavePhotoTask();
savePhotoTask.execute(bytes);
}
});
}
}
});
} else if (id == R.id.btn_change_camera) {
mCameraSource.release();
mCameraSource = null;
cameraId = cameraId == CameraSource.CAMERA_FACING_BACK ? CameraSource.CAMERA_FACING_FRONT : CameraSource.CAMERA_FACING_BACK;
createCameraSource(cameraId);
startCameraSource();
}
}
private class GraphicFaceTrackerFactory implements MultiProcessor.Factory<Face> {
#Override
public Tracker<Face> create(Face face) {
return new GraphicFaceTracker(mGraphicOverlay);
}
}
private class GraphicFaceTracker extends Tracker<Face> {
private GraphicOverlay mOverlay;
private FaceGraphic mFaceGraphic;
GraphicFaceTracker(GraphicOverlay overlay) {
mOverlay = overlay;
mFaceGraphic = new FaceGraphic(overlay);
}
#Override
public void onNewItem(int faceId, Face item) {
mFaceGraphic.setId(faceId);
}
#Override
public void onUpdate(FaceDetector.Detections<Face> detectionResults, Face face) {
mOverlay.add(mFaceGraphic);
mFaceGraphic.updateFace(face);
}
#Override
public void onMissing(FaceDetector.Detections<Face> detectionResults) {
mOverlay.remove(mFaceGraphic);
}
#Override
public void onDone() {
mOverlay.remove(mFaceGraphic);
}
}
class SavePhotoTask extends AsyncTask<byte[], String, String> {
#Override
protected String doInBackground(byte[]... data) {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "TRACKER_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
try {
File photo = File.createTempFile(imageFileName, ".jpg", storageDir);
FileOutputStream fos = new FileOutputStream(photo.getPath());
fos.write(data[0]);
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}}
NEXT.java
public class NEXT extends AppCompatActivity {
ImageView y;
Intent intent;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.next);
y = (ImageView) findViewById(R.id.myimage);
Bitmap bitmap = (Bitmap) intent.getParcelableExtra("key");
y.setImageBitmap(bitmap);
}}
Putin large data (>1Mo) can produce android.os.TransactionTooLargeException, ref :
The Binder transaction buffer has a limited fixed size, currently
1Mb, which is shared by all transactions in progress for the
process. Consequently this exception can be thrown when there are many
transactions in progress even when most of the individual transactions
are of moderate size.
The best way is to create a class and put your image into it, you can then access to it from any activity

How to save the captured image from camera in the phone memory to check the file size?

I am testing a camera application which captures high quality images. I want the captured image to be saved in the mobile memory (Internal or external) to check the details of the image.
I've the below code for capturing the image.
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomSheetBehavior;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.widget.Toast;
import com.otaliastudios.cameraview.CameraListener;
import com.otaliastudios.cameraview.CameraLogger;
import com.otaliastudios.cameraview.CameraOptions;
import com.otaliastudios.cameraview.CameraView;
import com.otaliastudios.cameraview.SessionType;
import com.otaliastudios.cameraview.Size;
import java.io.File;
public class CameraActivity extends AppCompatActivity implements View.OnClickListener, ControlView.Callback {
private CameraView camera;
private ViewGroup controlPanel;
private boolean mCapturingPicture;
private boolean mCapturingVideo;
// To show stuff in the callback
private Size mCaptureNativeSize;
private long mCaptureTime;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED,
WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);
setContentView(R.layout.activity_camera);
CameraLogger.setLogLevel(CameraLogger.LEVEL_VERBOSE);
camera = findViewById(R.id.camera);
camera.addCameraListener(new CameraListener() {
public void onCameraOpened(CameraOptions options) { onOpened(); }
public void onPictureTaken(byte[] jpeg) { onPicture(jpeg); }
#Override
public void onVideoTaken(File video) {
super.onVideoTaken(video);
onVideo(video);
}
});
findViewById(R.id.edit).setOnClickListener(this);
findViewById(R.id.capturePhoto).setOnClickListener(this);
findViewById(R.id.captureVideo).setOnClickListener(this);
findViewById(R.id.toggleCamera).setOnClickListener(this);
controlPanel = findViewById(R.id.controls);
ViewGroup group = (ViewGroup) controlPanel.getChildAt(0);
Control[] controls = Control.values();
for (Control control : controls) {
ControlView view = new ControlView(this, control, this);
group.addView(view, ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
}
controlPanel.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
BottomSheetBehavior b = BottomSheetBehavior.from(controlPanel);
b.setState(BottomSheetBehavior.STATE_HIDDEN);
}
});
}
private void message(String content, boolean important) {
int length = important ? Toast.LENGTH_LONG : Toast.LENGTH_SHORT;
Toast.makeText(this, content, length).show();
}
private void onOpened() {
ViewGroup group = (ViewGroup) controlPanel.getChildAt(0);
for (int i = 0; i < group.getChildCount(); i++) {
ControlView view = (ControlView) group.getChildAt(i);
view.onCameraOpened(camera);
}
}
private void onPicture(byte[] jpeg) {
mCapturingPicture = false;
long callbackTime = System.currentTimeMillis();
if (mCapturingVideo) {
message("Captured while taking video. Size="+mCaptureNativeSize, false);
return;
}
// This can happen if picture was taken with a gesture.
if (mCaptureTime == 0) mCaptureTime = callbackTime - 300;
if (mCaptureNativeSize == null) mCaptureNativeSize = camera.getPictureSize();
PicturePreviewActivity.setImage(jpeg);
Intent intent = new Intent(CameraActivity.this, PicturePreviewActivity.class);
intent.putExtra("delay", callbackTime - mCaptureTime);
intent.putExtra("nativeWidth", mCaptureNativeSize.getWidth());
intent.putExtra("nativeHeight", mCaptureNativeSize.getHeight());
startActivity(intent);
mCaptureTime = 0;
mCaptureNativeSize = null;
}
private void onVideo(File video) {
mCapturingVideo = false;
Intent intent = new Intent(CameraActivity.this, VideoPreviewActivity.class);
intent.putExtra("video", Uri.fromFile(video));
startActivity(intent);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.edit: edit(); break;
case R.id.capturePhoto: capturePhoto(); break;
case R.id.captureVideo: captureVideo(); break;
case R.id.toggleCamera: toggleCamera(); break;
}
}
#Override
public void onBackPressed() {
BottomSheetBehavior b = BottomSheetBehavior.from(controlPanel);
if (b.getState() != BottomSheetBehavior.STATE_HIDDEN) {
b.setState(BottomSheetBehavior.STATE_HIDDEN);
return;
}
super.onBackPressed();
}
private void edit() {
BottomSheetBehavior b = BottomSheetBehavior.from(controlPanel);
b.setState(BottomSheetBehavior.STATE_COLLAPSED);
}
private void capturePhoto() {
if (mCapturingPicture) return;
mCapturingPicture = true;
mCaptureTime = System.currentTimeMillis();
mCaptureNativeSize = camera.getPictureSize();
message("Capturing picture...", false);
camera.capturePicture();
}
private void captureVideo() {
if (camera.getSessionType() != SessionType.VIDEO) {
message("Can't record video while session type is 'picture'.", false);
return;
}
if (mCapturingPicture || mCapturingVideo) return;
mCapturingVideo = true;
message("Recording for 8 seconds...", true);
camera.startCapturingVideo(null, 8000);
}
private void toggleCamera() {
if (mCapturingPicture) return;
switch (camera.toggleFacing()) {
case BACK:
message("Switched to back camera!", false);
break;
case FRONT:
message("Switched to front camera!", false);
break;
}
}
#Override
public boolean onValueChanged(Control control, Object value, String name) {
if (!camera.isHardwareAccelerated() && (control == Control.WIDTH || control == Control.HEIGHT)) {
if ((Integer) value > 0) {
message("This device does not support hardware acceleration. " +
"In this case you can not change width or height. " +
"The view will act as WRAP_CONTENT by default.", true);
return false;
}
}
control.applyValue(camera, value);
BottomSheetBehavior b = BottomSheetBehavior.from(controlPanel);
b.setState(BottomSheetBehavior.STATE_HIDDEN);
message("Changed " + control.getName() + " to " + name, false);
return true;
}
//region Boilerplate
#Override
protected void onResume() {
super.onResume();
camera.start();
}
#Override
protected void onPause() {
super.onPause();
camera.stop();
}
#Override
protected void onDestroy() {
super.onDestroy();
camera.destroy();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
boolean valid = true;
for (int grantResult : grantResults) {
valid = valid && grantResult == PackageManager.PERMISSION_GRANTED;
}
if (valid && !camera.isStarted()) {
camera.start();
}
}
//endregion
}
I've also added the permissions to read and write the external storage.
But I just want to know the size of the picture once it is saved.
Adding the code to save the image -
public void KickOut(String filename,Bitmap bitmap){
ActivityCompat.requestPermissions(PicturePreviewActivity.this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
OutputStream outputStream;
File filepath=Environment.getExternalStorageDirectory();
// File dir=new File(filepath+"/Olaa/");
File dir=new File("/Environment.getExternalStoragePublicDirectory/Imgs/");
dir.mkdirs();
File file=new File(dir,"filename.png");
Toast.makeText(PicturePreviewActivity.this, file + " -> saved" , Toast.LENGTH_SHORT).show();
try{
outputStream=new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG,100,outputStream);
outputStream.flush();outputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// Toast.makeText(PicturePreviewActivity.this, filepath + " -> path" , Toast.LENGTH_SHORT).show();
}
You can check the size of the captured image you can also save the file in your custom folder.
you can get the result in onActivityResult() and get the image from the bundle and convert it into the byte and lengthbmp_KB will give you size in kb.
if (resultCode == RESULT_OK) {
//Image capture
if (requestCode == 1) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
byte[] imageInByte = bytes.toByteArray();
long lengthbmp = imageInByte.length;
// save on custom folder
File destination1 = createDirectoryAndSaveFile(thumbnail, System.currentTimeMillis() + ".jpg");
/* File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");*/
picturePath = "" + destination1;
// show image on gallery
scanGallery(getActivity(), picturePath);
long lengthbmp_KB = lengthbmp / 1024;
long length_MB = lengthbmp_KB / 1024;
}
you can save the file at your own folder
private File createDirectoryAndSaveFile(Bitmap imageToSave, String fileName) {
File direct = new File(Environment.getExternalStorageDirectory() + "/My Images");
if (!direct.exists()) {
File wallpaperDirectory = new File("/sdcard/MYfolder Images/");
wallpaperDirectory.mkdirs();
}
File file = new File(new File("/sdcard/Myfolder Images/"), fileName);
/* if (file.exists()) {
file.delete();
}*/
try {
FileOutputStream out = new FileOutputStream(file);
imageToSave.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
return file;
}
You can see your images in Gallery by using this MediaScannerConnection
private void scanGallery(Context cntx, String path) {
try {
MediaScannerConnection.scanFile(cntx, new String[]{path}, null, new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
and use this method in onActivityResult()
To check the size of image saved in phone memory , you could use Bitmapfactory.option
**BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filename, options);
int imageHeight = options.outHeight;
int imageWidth = options.outWidth;**
You can use this to save the file provided you've given the permissions in the manifest.
static final int REQUEST_TAKE_PHOTO = 1;
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// 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 = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
...
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.example.android.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
Take a look at the docs too over here.

Sending image from Android to PHP

I have tried 3 diffrent methods for sending a image from my Android to PHP.
All three gives the message "Missing inp_image name". I am thinking that I maybe am not sending the image as an image, but rather as some text ?
I am using this http request class in Android: https://github.com/kevinsawicki/http-request
Method 1 with encoding it to base64:
//String selectedFilePath = FilePath.getPath(context, imageUri);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4;
Bitmap bm = BitmapFactory.decodeFile(destImage,options);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG,40,baos);
byte[] byteImage_photo = baos.toByteArray(); // bitmap object
//generate base64 string of image
String encodedImage = Base64.encodeToString(byteImage_photo,Base64.DEFAULT);
// Send image
HttpRequest request = HttpRequest.post(apiUrl);
request.part("inp_image", encodedImage);
stringResponse = request.body();
Method 2 - sending a input stream of image
HttpRequest request = HttpRequest.post(apiUrl);
request.part("inp_image", in); // sending input stream
stringResponse = request.body();
Method 3 - sending file:
String sourceFilename= FilePath.getPath(context, imageUri);
HttpRequest request = HttpRequest.post(apiUrl);
request.part("inp_image", new File(sourceFilename)); // sending input stream
stringResponse = request.body();
Android Mainifest:
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
MainActivity:
package com.nettport.imageupload.imageupload;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.channels.FileChannel;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/* Check permission */
checkPermissionRead();
checkPermissionWrite();
/* Button listener */
buttonListener();
} // onCreate
private void checkPermissionRead(){
int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 1;
if (checkSelfPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (shouldShowRequestPermissionRationale(
android.Manifest.permission.READ_EXTERNAL_STORAGE)) {
// Explain to the user why we need to read the contacts
}
requestPermissions(new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE},
MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
// MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE is an
// app-defined int constant that should be quite unique
return;
}
} // checkPermissionRead
private void checkPermissionWrite(){
int MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE = 1;
if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (shouldShowRequestPermissionRationale(
android.Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
// Explain to the user why we need to read the contacts
}
requestPermissions(new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE},
MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);
// MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE is an
// app-defined int constant that should be quite unique
return;
}
} // checkPermissionRead
public void buttonListener() {
// Image button listener
Button buttonLoadImage = (Button) findViewById(R.id.buttonLoadImage);
buttonLoadImage.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick (View view){
// Load gallery
// User can select images and upload them
// Result will be in onActivityResult
Intent pickPhoto = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhoto , 1);//one can be replaced with any action code
}
});
// Camera
Button buttonLoadCamera = (Button) findViewById(R.id.buttonLoadCamera);
buttonLoadCamera.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick (View view){
// Load camera
// Result will be in onActivityResult
Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePicture, 0);//zero can be replaced with any action code
}
});
} // buttonListener
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
Uri selectedImageUri = data.getData();
// Set image
ImageView imageViewImage = (ImageView)findViewById(R.id.imageViewImage);
imageViewImage.setImageURI(selectedImageUri);
// Save image
String destinationFilename = savefile(selectedImageUri);
try {
InputStream in = getContentResolver().openInputStream(selectedImageUri);
TextView textViewDynamicText = (TextView) findViewById(R.id.textViewDynamicText); // Dynamic text
String apiURL = "https://xxxxxx.com/xxxxxx/image_upload.php";
UploadImage task = new UploadImage(this, apiURL, in, selectedImageUri, destinationFilename, textViewDynamicText, new UploadImage.TaskListener() {
#Override
public void onFinished(String result) {
// Do Something after the task has finished
imageUploadResult();
}
});
task.execute();
//in.close();
}
catch (java.io.FileNotFoundException e) {
Toast.makeText(this, "MainAcrivity java.io.FileNotFoundException: " + e.toString(), Toast.LENGTH_LONG).show();
}
catch (java.io.IOException e) {
Toast.makeText(this, "MainAcrivity java.io.IOException: " + e.toString(), Toast.LENGTH_LONG).show();
}
} // RESULT_OK
} // onActivityResult
public void imageUploadResult(){
// Dynamic text
TextView textViewDynamicText = (TextView)findViewById(R.id.textViewDynamicText);
Toast.makeText(this, textViewDynamicText.getText().toString(), Toast.LENGTH_SHORT).show();
} // imageUploadResult
public String savefile(Uri sourceuri) {
String sourceFilename= FilePath.getPath(this, sourceuri);
String destinationPath = android.os.Environment.getExternalStorageDirectory().getPath()+File.separatorChar+"/Upload";
String destinationFilename = destinationPath+"/upload_me.png";
// Make dir
File folder = new File(destinationPath);
boolean success = true;
if (!folder.exists()) {
success = folder.mkdir();
}
if (success) {
} else {
Toast.makeText(this, "Dir failed", Toast.LENGTH_LONG).show();
}
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bis = new BufferedInputStream(new FileInputStream(sourceFilename));
bos = new BufferedOutputStream(new FileOutputStream(destinationFilename, false));
byte[] buf = new byte[1024];
bis.read(buf);
do {
bos.write(buf);
} while(bis.read(buf) != -1);
// Toast.makeText(this, "Saved to " + destinationFilename, Toast.LENGTH_LONG).show();
}
catch (IOException e) {
e.printStackTrace();
Toast.makeText(this, "savefile#1: " + e.toString() + "\nFrom: " + sourceFilename, Toast.LENGTH_LONG).show();
}
finally {
try {
if (bis != null) bis.close();
if (bos != null) bos.close();
}
catch (IOException e) {
e.printStackTrace();
Toast.makeText(this, "savefile#2: " + e.toString(), Toast.LENGTH_LONG).show();
}
}
return destinationFilename;
}
}
UploadImage class:
package com.nettport.imageupload.imageupload;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Base64;
import android.widget.TextView;
import android.widget.Toast;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
/**
* Created by bruker on 08.08.2017.
* Updated
*/
public class UploadImage extends AsyncTask<String, Void, String> {
/* Class variables */
private Context context; // Holder (this)
private String apiUrl; // URL for image upload form, example http://website.com/image_upload.php
private TextView dynamicText;
private InputStream in;
private Uri imageUri;
private String destImage;
private final UploadImage.TaskListener taskListener; // This is the reference to the associated listener
public interface TaskListener {
public void onFinished(String result);
}
/*- Constructor GET, SEND --------------------------------------------------------------- */
public UploadImage(Context ctx, String applicationPIUrl, InputStream input, Uri selectedImageUri, String destinationFilename, TextView textViewDynamicText, UploadImage.TaskListener listener) {
context = ctx;
apiUrl = applicationPIUrl;
in = input;
imageUri = selectedImageUri;
destImage = destinationFilename;
dynamicText = textViewDynamicText;
this.taskListener = listener; // The listener reference is passed in through the constructor
}
#Override
protected void onPreExecute() {
super.onPreExecute();
dynamicText.setText(dynamicText.getText().toString() + "\n" + "Loading...");
}
#Override
protected String doInBackground(String... params) {
// Run methods
String stringResponse ="";
try {
try{
// Method 1 - Base 64
/*
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4;
Bitmap bm = BitmapFactory.decodeFile(destImage,options);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG,40,baos);
byte[] byteImage_photo = baos.toByteArray(); // bitmap object
//generate base64 string of image
String encodedImage = Base64.encodeToString(byteImage_photo,Base64.DEFAULT);
// Send image
HttpRequest request = HttpRequest.post(apiUrl);
request.part("inp_image", encodedImage);
stringResponse = request.body();
*/
// Method 2 - Input stream
/*
HttpRequest request = HttpRequest.post(apiUrl);
request.part("inp_image", in); // sending input stream
stringResponse = request.body();
*/
// Method 3 - File
String sourceFilename= FilePath.getPath(context, imageUri);
HttpRequest request = HttpRequest.post(apiUrl);
request.part("inp_image", new File(sourceFilename)); // sending input stream
stringResponse = request.body();
}
catch (Exception e){
return e.toString();
}
}
catch(Exception e){
return e.toString();
}
return stringResponse;
}
#Override
protected void onPostExecute(String result) {
// Set text view with result string
if(dynamicText == null){
Toast.makeText(context, "NULL", Toast.LENGTH_SHORT).show();
}
else {
dynamicText.setText(dynamicText.getText().toString() + "\n" + result);
}
// In onPostExecute we check if the listener is valid
if(this.taskListener != null) {
// And if it is we call the callback function on it.
this.taskListener.onFinished(result);
}
}
#Override
protected void onProgressUpdate(Void... values) {}
}
PHP Script:
<?php
/**
*
* File: image_upload.php
* Date 13:05 04.08.2017
* Version 1
* Copyright (c) 2017 S. A. Ditlefsen
* License: http://opensource.org/licenses/gpl-license.php GNU Public License
*
*/
/*- Get extention ---------------------------------------------------------------------- */
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
/*- Path -------------------------------------------------------------------------------- */
if(!(is_dir("_images"))){
mkdir("_images");
}
/*- Script start ------------------------------------------------------------------------ */
$name = stripslashes($_FILES['inp_image']['name']);
if($name){
$extension = getExtension($name);
$extension = strtolower($extension);
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) {
echo"unknown_file_extension";
}
else{
$date_time = date("Y-m-d_h-i-s");
$new_name = $date_time . ".png";
$new_path = "_images/";
$uploaded_file = $new_path . $new_name;
// Upload file
if (move_uploaded_file($_FILES['inp_image']['tmp_name'], $uploaded_file)) {
// Get image size
$file_size = filesize($uploaded_file);
// Check with and height
list($width,$height) = getimagesize($uploaded_file);
if($width == "" OR $height == ""){
echo"getimagesize_failed";
}
else{
// Resize to $settings_image_width
$newwidth=1000;
$newheight=($height/$width)*$newwidth; // 667
$tmp=imagecreatetruecolor($newwidth,$newheight);
if($extension=="jpg" || $extension=="jpeg" ){
$src = imagecreatefromjpeg($uploaded_file);
}
else if($extension=="png"){
$src = imagecreatefrompng($uploaded_file);
}
else{
$src = imagecreatefromgif($uploaded_file);
}
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight, $width,$height);
imagepng($tmp,$uploaded_file);
imagedestroy($tmp);
echo"$new_name";
} // width height
} // move_uploaded_file
else{
switch ($_FILES['inp_food_image_b']['error']) {
case UPLOAD_ERR_OK:
echo"image_to_big";
break;
case UPLOAD_ERR_NO_FILE:
echo"no_file_uploaded";
break;
case UPLOAD_ERR_INI_SIZE:
echo"to_big_size_in_configuration";
break;
case UPLOAD_ERR_FORM_SIZE:
echo"to_big_size_in_form";
break;
default:
echo"unknown_error";
break;
}
}
} // extention
} // name
else{
echo"Missing inp_image name";
}
?>
try this and it is working for me ,
String imgstring = getStringImage(bitmap)
public String getStringImage(Bitmap bmp) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
volley
public void addimage() {
String link = CommonVariables.SERVER_IP + "/uploadimage.php";
StringRequest request = new StringRequest(Request.Method.POST, link, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
if (volleyError != null && volleyError.getMessage() != null) {
Toast.makeText(getContext(), volleyError.getMessage(), Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getContext(), "Something went wrong", Toast.LENGTH_LONG).show();
}
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("imagename", "yourimagename");
params.put("imagecode", imageString);
return params;
}
};
RetryPolicy mRetryPolicy = new DefaultRetryPolicy(
0,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
request.setRetryPolicy(mRetryPolicy);
queue.add(request);
}
php
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
$imgcode = $_POST['imagecode'];
$imagename = $_POST['imagename'];
require_once('dbconnect.php');
// this is ths path where your image is stored in the file in server
$path = "images/$imagename.jpg";
$sql = "INSERT INTO productlist(proimagename)
VALUES ('$imagename')";
if(mysqli_query($con,$sql)){
file_put_contents($path,base64_decode($imgcode));
echo "1";
}
mysqli_close($con);
}else{
echo "0";
}

How to show current location in IndoorAtlas Floorplan image?

I load the Indoor Atlas floorplan image but how can i show my position on that image..
Also this image is static please help.
Code for loading floorplan is below.
public void loadFloorPlanImage(FloorPlan floorPlan)
{
BitmapFactory.Options options = createBitmapOptions(floorPlan);
FutureResult<Bitmap> result = mIndoorAtlas.fetchFloorPlanImage(floorPlan,options);
result.setCallback(new ResultCallback<Bitmap>() {
#Override
public void onResult(final Bitmap result) {
runOnUiThread(new Runnable() {
#Override
public void run() {
ImageView imageView = (ImageView) findViewById(R.id.imageView);
imageView.setImageBitmap(result);
}
});
}
});
}
I got the position time to time i just mark that position on the ImageView my code is..
public void onServiceUpdate(ServiceState state) {
double x1 = state.getMetricPoint().getX();
double y1 = state.getMetricPoint().getY();
float x = (float) x1;
float y = (float) y1;
//Paint paint = new Paint();
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setAntiAlias(true);
paint.setColor(Color.RED);
Bitmap workingBitmap = Bitmap.createBitmap(image);
Bitmap mutableBitmap = workingBitmap.copy(Bitmap.Config.ARGB_8888, true);
Canvas canvas = new Canvas(mutableBitmap);
// canvas.drawCircle(x, y, 100, paint);
canvas.drawCircle(50, 50, 10, paint);
imageView.setAdjustViewBounds(true);
imageView.setImageBitmap(image);
}
But it does not work. Please help Thanks
import java.io.IOException;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import com.indooratlas.android.CalibrationState;
import com.indooratlas.android.FloorPlan;
import com.indooratlas.android.FutureResult;
import com.indooratlas.android.IndoorAtlas;
import com.indooratlas.android.IndoorAtlasException;
import com.indooratlas.android.IndoorAtlasFactory;
import com.indooratlas.android.IndoorAtlasListener;
import com.indooratlas.android.ResultCallback;
import com.indooratlas.android.ServiceState;
/**
* <p>
* Activity to demonstrate basic use of IndoorAtlas SDK. If there are no public
* maps around your location, you can create a map of your own and upload it to
* IndoorAtlas servers. Read more on how to do this from:
* http://developer.indooratlas.com.
* </p>
* <p/>
* <p>
* To run this demo, you will also need your applications API key/secret and
* identifiers for the floor plan from http://developer.indooratlas.com.
* </p>
* <p/>
*/
public class MainActivity extends Activity implements IndoorAtlasListener {
private static final String TAG = "MainActivity";
// private ListView mLogView;
// private LogAdapter mLogAdapter;
private IndoorAtlas mIndoorAtlas;
private boolean mIsPositioning;
private StringBuilder mSharedBuilder = new StringBuilder();
private String apiKey = "YOU API KEY";
private String apiSecret = "YOUR SECRET KEY";
private String floorPlanId = "CUSTOM FLOOR PLAN ID";
private String venueId = "CUSTOM VENUE ID";
private String floorId = "CUSTOM FLOOR ID";
private FloorPlan mFloorPlan;
private ImageView imageView1;
private Bitmap bitmap;
private Bitmap copy;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map_layout);
imageView1 = (ImageView) findViewById(R.id.imageView1);
// mLogView = (ListView) findViewById(R.id.list);
// mLogAdapter = new LogAdapter(this);
// mLogView.setAdapter(mLogAdapter);
initIndoorAtlas();
}
#Override
protected void onDestroy() {
super.onDestroy();
tearDown();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_clear_log:
// mLogAdapter.clear();
return true;
case R.id.action_toggle_positioning:
togglePositioning();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void tearDown() {
if (mIndoorAtlas != null) {
mIndoorAtlas.tearDown();
}
}
private void stopPositioning() {
mIsPositioning = false;
if (mIndoorAtlas != null) {
log("Stop positioning");
mIndoorAtlas.stopPositioning();
}
}
private void startPositioning() {
if (mIndoorAtlas != null) {
log(String
.format("startPositioning, venueId: %s, floorId: %s, floorPlanId: %s",
venueId, floorId, floorPlanId));
try {
mIndoorAtlas.startPositioning(venueId, floorId, floorPlanId);
mIsPositioning = true;
} catch (IndoorAtlasException e) {
log("startPositioning failed: " + e);
}
} else {
log("calibration not ready, cannot start positioning");
}
}
private void togglePositioning() {
if (mIsPositioning) {
stopPositioning();
} else {
startPositioning();
}
}
private void initIndoorAtlas() {
try {
log("Connecting with IndoorAtlas, apiKey: " + apiKey);
// obtain instance to positioning service, note that calibrating
// might begin instantly
mIndoorAtlas = IndoorAtlasFactory.createIndoorAtlas(
getApplicationContext(), this, // IndoorAtlasListener
apiKey, apiSecret);
log("IndoorAtlas instance created");
FutureResult<FloorPlan> result = mIndoorAtlas
.fetchFloorPlan(floorPlanId);
result.setCallback(new ResultCallback<FloorPlan>() {
#Override
public void onResult(final FloorPlan result) {
mFloorPlan = result;
loadFloorPlanImage(result);
}
#Override
public void onApplicationError(IndoorAtlasException arg0) {
// TODO Auto-generated method stub
}
#Override
public void onSystemError(IOException arg0) {
// TODO Auto-generated method stub
}
// handle error conditions too
});
try {
Log.d("abcd", "helo14");
mIndoorAtlas.startPositioning(venueId, floorId, floorPlanId);
Log.d("abcd", "helo1");
} catch (IndoorAtlasException e) {
// TODO Auto-generated catch block
Log.d("abcd", "helo");
e.printStackTrace();
}
togglePositioning();
} catch (IndoorAtlasException ex) {
Log.e("IndoorAtlas", "init failed", ex);
log("init IndoorAtlas failed, " + ex.toString());
}
}
private void updateImageViewInUiThread(final Bitmap result) {
runOnUiThread(new Runnable() {
#Override
public void run() {
bitmap = result;
imageView1.setImageBitmap(result);
}
});
}
void loadFloorPlanImage(FloorPlan floorPlan) {
BitmapFactory.Options options = createBitmapOptions(floorPlan);
FutureResult<Bitmap> result = mIndoorAtlas.fetchFloorPlanImage(
floorPlan, options);
result.setCallback(new ResultCallback<Bitmap>() {
#Override
public void onResult(final Bitmap result) {
// now you have floor plan bitmap, do something with it
updateImageViewInUiThread(result);
}
#Override
public void onApplicationError(IndoorAtlasException arg0) {
// TODO Auto-generated method stub
}
#Override
public void onSystemError(IOException arg0) {
// TODO Auto-generated method stub
}
// handle error conditions too
});
}
private void log(final String msg) {
Log.d(TAG, msg);
runOnUiThread(new Runnable() {
#Override
public void run() {
// mLogAdapter.add(msg);
// mLogAdapter.notifyDataSetChanged();
}
});
}
/* IndoorAtlasListener interface */
/**
* This is where you will handle location updates.
*/
#Override
public void onServiceUpdate(ServiceState state) {
Log.d("abcd", "testttt");
final Bitmap icon = BitmapFactory.decodeResource(
getApplicationContext().getResources(), R.drawable.loc_img);
// TODO Auto-generated method stub
final int i = state.getImagePoint().getI();
final int j = state.getImagePoint().getJ();
Log.d("abcd", "" + i + " " + j);
runOnUiThread(new Runnable() {
#Override
public void run() {
if (bitmap != null) {
Bitmap copy2 = bitmap.copy(bitmap.getConfig(), true);
Canvas canvas = new Canvas(copy2);
Paint paint = new Paint(Paint.FILTER_BITMAP_FLAG);
canvas.drawBitmap(icon, i, j, paint);
imageView1.setImageBitmap(copy2);
}
}
});
mSharedBuilder.setLength(0);
mSharedBuilder.append("Location: ").append("\n\troundtrip : ")
.append(state.getRoundtrip()).append("ms").append("\n\tlat : ")
.append(state.getGeoPoint().getLatitude()).append("\n\tlon : ")
.append(state.getGeoPoint().getLongitude())
.append("\n\tX [meter] : ")
.append(state.getMetricPoint().getX())
.append("\n\tY [meter] : ")
.append(state.getMetricPoint().getY())
.append("\n\tI [pixel] : ")
.append(state.getImagePoint().getI())
.append("\n\tJ [pixel] : ")
.append(state.getImagePoint().getJ()).append("\n\theading : ")
.append(state.getHeadingDegrees()).append("\n\tuncertainty: ")
.append(state.getUncertainty());
log(mSharedBuilder.toString());
}
private BitmapFactory.Options createBitmapOptions(FloorPlan floorPlan) {
BitmapFactory.Options options = null;
int reqWidth = 2048;
int reqHeight = 2048;
final int width = (int) floorPlan.dimensions[0];
final int height = (int) floorPlan.dimensions[1];
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
if (options != null) {
options.inSampleSize = inSampleSize;
}
return options;
}
private Bitmap overlay(Bitmap bmp1, Bitmap bmp2) {
Bitmap bmOverlay = Bitmap.createBitmap(bmp1.getWidth(),
bmp1.getHeight(), bmp1.getConfig());
Canvas canvas = new Canvas(bmOverlay);
canvas.drawBitmap(bmp1, new Matrix(), null);
canvas.drawBitmap(bmp2, new Matrix(), null);
return bmOverlay;
}
#Override
public void onServiceFailure(int errorCode, String reason) {
log("onServiceFailure: reason : " + reason);
}
#Override
public void onServiceInitializing() {
log("onServiceInitializing");
}
#Override
public void onServiceInitialized() {
log("onServiceInitialized");
}
#Override
public void onInitializationFailed(final String reason) {
log("onInitializationFailed: " + reason);
}
#Override
public void onServiceStopped() {
log("onServiceStopped");
}
#Override
public void onCalibrationStatus(CalibrationState calibrationState) {
log("onCalibrationStatus, percentage: "
+ calibrationState.getPercentage());
}
/**
* Notification that calibration has reached level of quality that provides
* best possible positioning accuracy.
*/
#Override
public void onCalibrationReady() {
log("onCalibrationReady");
}
#Override
public void onNetworkChangeComplete(boolean success) {
}
/**
* #deprecated this callback is deprecated as of version 1.4
*/
#Override
public void onCalibrationInvalid() {
}
/**
* #deprecated this callback is deprecated as of version 1.4
*/
#Override
public void onCalibrationFailed(String reason) {
}
}
This code may help you.. And refer this link

Categories

Resources