image path from android to php web interface - java

I have an android app that captures images and sends them to firebase storage. In my web interface I retrieve the url of these images and make it like a video, but this way the image transitions are too slow. What would be the best way for me to pass the url of these images from the android app to the php web interface?
Would it be faster via socket?
Screenshot.java
private class ImageAvailableListener implements ImageReader.OnImageAvailableListener {
#Override
public void onImageAvailable(ImageReader reader) {
FileOutputStream fos = null;
Bitmap bitmap = null;
try (Image image = mImageReader.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);
IMAGES_PRODUCED++;
Log.e(TAG, "captured image: " + IMAGES_PRODUCED);
//TRANSFOMAR BITMAP EM ARRAY DE BYTES
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 0, baos);
byte[] dadosImagem = baos.toByteArray();
//criar nome unico de imagem
//String nomeImagem = UUID.randomUUID().toString();
StorageReference imagemRef = storageReference
.child("imagens")
.child("screenshot")
.child(idUser)
.child(IMAGES_PRODUCED+".jpeg");
//fazer upload da imagem
UploadTask uploadTask = imagemRef.putBytes(dadosImagem);
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
//em versoes anteriores do a gente recuperava assim taskSnapshot.getDownloadUrl();
//recuperar a url para inserir no realtime
imagemRef.getDownloadUrl().addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
//aqui temos a url da imagem
String url = task.getResult().toString();
Log.d("TAG", IMAGES_PRODUCED + url);
//grava a url recuperada da imagem no realtime
Imagem imagem = new Imagem();
imagem.setUrl(url);
imagem.setIdUsuario(idUser);
imagem.salvarImagem();
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("message", url);
jsonObject.put("byServer", false);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
});
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

Related

Save an Image with TextureView?

I hope you can fix my problem:
I have got a textureview to takes photos but when he capture photos, the file who need to contain the picture is empty. I don't know where and what is the problem. I just think that the problem is when the file is created. Thank you to help me.
This is a part of my code :
private void takePicture() throws CameraAccessException, IOException {
if(cameraDevice == null){
return;
}
CameraManager manager = (CameraManager) Objects.requireNonNull(getContext()).getSystemService(Context.CAMERA_SERVICE);
CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraDevice.getId());
Size[] jpegSizes = null;
jpegSizes = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP).getOutputSizes(ImageFormat.JPEG);
int width = 640;
int height = 480;
if(jpegSizes!=null && jpegSizes.length>0){
width = jpegSizes[0].getWidth();
height = jpegSizes[0].getHeight();
}
ImageReader reader = ImageReader.newInstance(width,height, ImageFormat.JPEG, 1);
List<Surface> outputSurface = new ArrayList<>(2);
outputSurface.add(reader.getSurface());
outputSurface.add(new Surface(textureView.getSurfaceTexture()));
final CaptureRequest.Builder captureBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
captureBuilder.addTarget(reader.getSurface());
captureBuilder.set(CaptureRequest.CONTROL_MODE,CameraMetadata.CONTROL_MODE_AUTO);
int rotation = Objects.requireNonNull(getActivity()).getWindowManager().getDefaultDisplay().getRotation();
captureBuilder.set(CaptureRequest.JPEG_ORIENTATION,ORIENTATIONS.get(rotation));
// First I get the path to gallery and crate new Album to my app
File file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
mImageFolder = new File(file, "Fluico");
if (!mImageFolder.exists()) {
if (!mImageFolder.mkdirs()) {
Log.d("Fluicophoto", "failed to create directory");
}
}
/*Second I cut mFile = new File(getActivity().getExternalFilesDir(null), "pic.jpg");
from onActivityCreated and add here with the new path from my Album*/
#SuppressLint("SimpleDateFormat") String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String prepend = "IMAGE_" + timestamp + "_";
file = File.createTempFile(prepend, ".jpg", mImageFolder);
Toast.makeText(getContext(), "file need to be save", Toast.LENGTH_SHORT).show();
ImageReader.OnImageAvailableListener readerListener = new ImageReader.OnImageAvailableListener() {
#Override
public void onImageAvailable(ImageReader reader) {
Image image = null;
image = reader.acquireLatestImage();
ByteBuffer buffer = image.getPlanes()[0].getBuffer();
byte[] bytes = new byte[buffer.capacity()];
buffer.get(bytes);
try {
save(bytes);
} finally {
image.close();
}
}
};
reader.setOnImageAvailableListener(readerListener,mBackgroundHandler);
final CameraCaptureSession.CaptureCallback captureListener = new CameraCaptureSession.CaptureCallback() {
#Override
public void onCaptureCompleted(CameraCaptureSession session, CaptureRequest request, TotalCaptureResult result) {
super.onCaptureCompleted(session, request, result);
Toast.makeText(getContext(), "saved", Toast.LENGTH_SHORT).show();
try{
createCameraPreview();
}catch (CameraAccessException e){
Toast.makeText(getContext(), "capture not comleted", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
};
cameraDevice.createCaptureSession(outputSurface, new CameraCaptureSession.StateCallback() {
#Override
public void onConfigured( CameraCaptureSession session) {
try {
session.capture(captureBuilder.build(), captureListener, mBackgroundHandler);
} catch (CameraAccessException e) {
e.printStackTrace();
Toast.makeText(getContext(), "capture not configured", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onConfigureFailed( CameraCaptureSession session) {
}
},mBackgroundHandler);
}
private void save(byte[] bytes) {
OutputStream outputStream = null;
try {
outputStream = new FileOutputStream(file);
outputStream.write(bytes);
outputStream.close();
Toast.makeText(getContext(), "it's good", Toast.LENGTH_SHORT).show();
}catch (IOException e){
Toast.makeText(getContext(), "file not found", Toast.LENGTH_SHORT).show();
}
}
Try with below code:
File myDir;
String fname;
String id = "123456";
int count = 0;
String root = Environment.getExternalStorageDirectory().toString();
myDir = new File(root + "/PhotoApp/" + id);
myDir.mkdirs();
count++;
counter.setText(String.valueOf(count));
fname = "" + id + "-" + count + ".jpg";
File file = new File(myDir, fname);
if (file.exists()) file.delete();
This code will create a folder PhotoApp and inside the folder, all the images will store.
You can get full code with the camera in my GitHub:
Link: https://github.com/abhishekhzb/quick_camera

How to share image with a button? [duplicate]

This question already has answers here:
How to use "Share image using" sharing Intent to share images in android?
(17 answers)
Closed 2 years ago.
I am making QR code generator
So far I made a generator button and save button.
It works fine.
I am trying to work on the sharing button.
It takes a few days to figure out as a beginner and still I cannot make it work.
At this code, if I click share, then the app closes.
/**Barcode share*/
findViewById(R.id.share_barcode).setOnClickListener(v -> {
Bitmap b = BitmapFactory.decodeResource(getResources(),R.id.qr_image);
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/jpeg");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(getContentResolver(), b, "Title", null);
Uri imageUri = Uri.parse(path);
share.putExtra(Intent.EXTRA_STREAM, imageUri);
startActivity(Intent.createChooser(share, "Select"));
});
I guessed the problem was path.
I use savepath to save qr code image. And then maybe it conflicts with String path
So I tried String savePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) + "/Camera/";;
It's not working. So maybe it's different problem and I don't know how to fix it.
Could you show me how to fix?
MainActivity
public class MainActivity extends AppCompatActivity {
private String inputValue;
private String savePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) + "/Camera/";
private Bitmap bitmap;
private QRGEncoder qrgEncoder;
private ImageView qrImage;
private EditText edtValue;
private AppCompatActivity activity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
qrImage = findViewById(R.id.qr_image);
edtValue = findViewById(R.id.edt_value);
activity = this;
/**Barcode Generator*/
findViewById(R.id.generate_barcode).setOnClickListener(view -> {
inputValue = edtValue.getText().toString().trim();
if (inputValue.length() > 0) {
WindowManager manager = (WindowManager) getSystemService(WINDOW_SERVICE);
Display display = manager.getDefaultDisplay();
Point point = new Point();
display.getSize(point);
int width = point.x;
int height = point.y;
int smallerDimension = width < height ? width : height;
smallerDimension = smallerDimension * 3 / 4;
qrgEncoder = new QRGEncoder(
inputValue, null,
QRGContents.Type.TEXT,
smallerDimension);
qrgEncoder.setColorBlack(Color.BLACK);
qrgEncoder.setColorWhite(Color.WHITE);
try {
bitmap = qrgEncoder.getBitmap();
qrImage.setImageBitmap(bitmap);
} catch (Exception e) {
e.printStackTrace();
}
} else {
edtValue.setError(getResources().getString(R.string.value_required));
}
});
/**Barcode save*/
findViewById(R.id.save_barcode).setOnClickListener(v -> {
String filename = edtValue.getText().toString().trim();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
try {
ContentResolver resolver = getContentResolver();
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, filename + ".jpg");
contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "image/jpg");
contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DCIM);
Uri imageUri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
OutputStream fos = resolver.openOutputStream(Objects.requireNonNull(imageUri));
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
Objects.requireNonNull(fos).close();
Toast toast= Toast.makeText(getApplicationContext(),
"Image Saved. Check your gallery.", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.TOP|Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
edtValue.setText(null);
} catch (IOException e) {
e.printStackTrace();
}
} else {
if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
try {
boolean save = new QRGSaver().save(savePath, filename, bitmap, QRGContents.ImageType.IMAGE_JPEG);
String result = save ? "Image Saved. Check your gallery." : "Image Not Saved";
Toast.makeText(activity, result, Toast.LENGTH_LONG).show();
edtValue.setText(null);
} catch (Exception e) {
e.printStackTrace();
}
} else {
ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
}
}
});
/**Barcode share*/
findViewById(R.id.share_barcode).setOnClickListener(v -> {
Bitmap b = BitmapFactory.decodeResource(getResources(),R.id.qr_image);
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/jpeg");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(getContentResolver(), b, "Title", null);
Uri imageUri = Uri.parse(path);
share.putExtra(Intent.EXTRA_STREAM, imageUri);
startActivity(Intent.createChooser(share, "Select"));
});
}
}
I think you can solve this by:
Saving the bitmap in a file.
Then sharing the URI of that file in the intent.
In the code below, I am saving the image at the app level directory, you can choose your own and the code is written in kotlin.
Note: If you are using an app-level directory for saving the image then you must use the file provide to get the URI else it may result in FileUriExposedException
try {
val file = File(getExternalFilesDir(null),System.currentTimeMillis().toString() + ".png")
file.createNewFile()
val b = imageView.drawable.toBitmap()
FileOutputStream(file).use { out ->
b.compress(Bitmap.CompressFormat.PNG, 100, out)
}
val share = Intent(Intent.ACTION_SEND)
share.type = "image/jpeg"
val photoURI = FileProvider.getUriForFile(this, applicationContext.packageName.toString() + ".provider", file)
share.putExtra(Intent.EXTRA_STREAM, photoURI)
startActivity(Intent.createChooser(share, "Share Image"))
Toast.makeText(this, "Completed!!", Toast.LENGTH_SHORT).show()
} catch (e: IOException) {
e.printStackTrace()
Toast.makeText(this, e.message, Toast.LENGTH_SHORT).show()
}
In JAVA:
public void shareImage(Activity activity, ImageView imageView) {
try {
File file = new File(activity.getExternalFilesDir(null), System.currentTimeMillis() + ".png");
file.createNewFile();
Bitmap bitmap = drawableToBitmap(imageView.getDrawable());
FileOutputStream fOut = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 85, fOut);
fOut.flush();
fOut.close();
Intent share = new Intent("android.intent.action.SEND");
share.setType("image/jpeg");
Uri photoURI = FileProvider.getUriForFile(activity,activity.getPackageName(), file);
share.putExtra("android.intent.extra.STREAM", photoURI);
activity.startActivity(Intent.createChooser(share, "Share Image"));
} catch (Exception var14) {
}
}
public static Bitmap drawableToBitmap (Drawable drawable) {
Bitmap bitmap;
if (drawable instanceof BitmapDrawable) {
BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
if(bitmapDrawable.getBitmap() != null) {
return bitmapDrawable.getBitmap();
}
}
if(drawable.getIntrinsicWidth() <= 0 || drawable.getIntrinsicHeight() <= 0) {
bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888); // Single color bitmap will be created of 1x1 pixel
} else {
bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
}
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
return bitmap;
}

Save drawable into parse

I saved into my project a drawable R.drawable.descarga what I need to do I that when there is no file to upload to parse it uploads this one.
This is my code.
if (requestCode == REQUEST_GALLERY_PHOTO7 && resultCode == RESULT_OK) {
Uri imageUri = data.getData();
InputStream inputStream;
try {
inputStream = getActivity().getApplicationContext().getContentResolver().openInputStream(imageUri);
Bitmap image = BitmapFactory.decodeStream(inputStream);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
ParseFile fileInmoFotoPrinci = new ParseFile("image.jpg", byteArray);
inmoFoto8.setImageBitmap(image);
if(fileInmoFotoPrinci!=null) {
grabarImagenPrinc.put("imagen7", fileInmoFotoPrinci);
}else{
Drawable myDrawable = getResources().getDrawable(R.drawable.descarga);
Bitmap myLogo = ((BitmapDrawable) myDrawable).getBitmap();
// FileOutputStream fos = new FileOutputStream(myDrawable);
//
// File file=myLogo.compress(Bitmap.CompressFormat.PNG, 100, fos);
grabarImagenPrinc.put("imagen7", myDrawable);
}
grabarImagenPrinc.saveInBackground();
} catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(getActivity(), "No fue posible abrir la imagen", Toast.LENGTH_LONG).show();
}
}
i would be having the trouble in this part ...
Drawable myDrawable = getResources().getDrawable(R.drawable.descarga);
Bitmap myLogo = ((BitmapDrawable) myDrawable).getBitmap();
// FileOutputStream fos = new FileOutputStream(myDrawable);
//
// File file=myLogo.compress(Bitmap.CompressFormat.PNG, 100, fos);
grabarImagenPrinc.put("imagen7", myDrawable);
i have tried to apply many StackOverflow post in this part but nothing seems to work.
The Documentation says this but I don't really understand it...
byte[] data = "Working at Parse is great!".getBytes();
ParseFile file = new ParseFile("resume.txt", data);
Also tried this code in the else statement.
Drawable d = null; // the drawable (Captain Obvious, to the rescue!!!)
Bitmap bitmap = ((BitmapDrawable)d).getBitmap();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
byte[] bitmapdata = stream.toByteArray();
ParseFile file = new ParseFile("image.jpeg", bitmapdata);
grabarImagenPrinc.put("imagen7",file);
My problem is that the drawable isnt saving to parse how it should do.
This is the code update!.
private void queryEmpresa() {
/**Ojo no es que no este sirviendo el metodo sino que el tipo de empresa asignado al usuario
* no concuerda para que llene el recycler*/
ParseQuery<ParseUser> query = ParseUser.getQuery();
query.whereEqualTo("objectId", ParseUser.getCurrentUser().getObjectId());
query.include("Empresa");
query.getInBackground(ParseUser.getCurrentUser().getObjectId(), new GetCallback<ParseUser>() {
public void done(ParseUser object, ParseException e) {
if (e == null) {
// object will be your user and you should be able to retrieve Empresa like this
empresa = object.getParseObject("Empresa");
if (empresa != null) {
ParseObject grabarImagenPrinc = new ParseObject("PropiedadesInmobiliarias");
stringEmpresa = empresa.getObjectId();
ParseObject entity = new ParseObject("PropiedadesInmobiliarias");
Bitmap bm = ((BitmapDrawable) inmoFotoPrincipal.getDrawable()).getBitmap();
if(bm.equals("")) {
ByteArrayOutputStream myLogoStream = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, myLogoStream);
byte[] myLogoByteArray = myLogoStream.toByteArray();
bm.recycle();
ParseFile myLogoFile = new ParseFile("mylogo.png", myLogoByteArray);
grabarImagenPrinc.put("imagen7", myLogoFile);
grabarImagenPrinc.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
}
});
}
entity.put("numeroBanos", edittextNumeroDeBanos.getText().toString().trim());
entity.put("descripcionAdicionalPropiedad", edittextDescripcion.getText().toString().trim());
entity.put("Empresa", ParseObject.createWithoutData("Empresa", stringEmpresa));
entity.put("NombrePropiedad", edittextNombrePropiedad.getText().toString().trim());
entity.put("Precio", edittextPrecio.getText().toString().trim());
String xx=edittextNumeroHabitaciones.getText().toString().trim();
entity.put("numeroDeHabitaciones", edittextNumeroHabitaciones.getText().toString().trim());
String xy=edittextMetrosCuadrados.getText().toString().trim();
entity.put("metrosCuadrados", edittextMetrosCuadrados.getText().toString().trim());
entity.put("valorAdministracion", edittextValorAdmin.getText().toString().trim());
entity.put("Parqueaderos", edittextParqueaderos.getText().toString().trim());
entity.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
Log.i("XX","este es el error de porque no salva",e);
Intent intent = new Intent(getActivity(), MainActivity.class);
getActivity().startActivity(intent);
}
});
} else {
// something went wrong. It would be good to log.
}
}
}
});
}
This is used in a button to save with an on click listener...
look at this i made a different approach taking your suggestions davi.
try:
...
Drawable myDrawable = getResources().getDrawable(R.drawable.descarga);
Bitmap myLogo = ((BitmapDrawable) myDrawable).getBitmap();
ByteArrayOutputStream myLogoStream = new ByteArrayOutputStream();
myLogo.compress(Bitmap.CompressFormat.PNG, 100, myLogoStream);
byte[] myLogoByteArray = myLogoStream.toByteArray();
myLogo.recycle();
ParseFile myLogoFile = new ParseFile("mylogo.png", myLogoByteArray);
grabarImagenPrinc.put("imagen7", myLogoFile);
...

Getting bitmap null while converting url to bitmap

I want to download the image from server and convert it to bitmap. I tried to download the image and convert it to bitmap but it returns null. I get bitmap as null.
To convert image to bitmap I have created one asyncTask.
Passing url to Async task :
String url = ServiceUrl.getBaseUrl() + ServiceUrl.getImageUserUrl() + profileImage;
Log.e("url", url);
new ImageUserTask(mContext, url, profileImage).execute();
ImageUserAsync Task:
public class ImageUserTask extends AsyncTask<Void, Void, Bitmap> {
String imageprofile;
private String url;
private Bitmap mBitmap;
private Context mContext;
public ImageUserTask(Context context, String url, String imageprofile) {
this.url = url;
this.imageprofile = imageprofile;
this.mContext = context;
}
#Override
protected Bitmap doInBackground(Void... params) {
try {
//Url
URL urlConnection = new URL(url);
//Conntecting httpUrlConnection
HttpURLConnection connection = (HttpURLConnection) urlConnection.openConnection();
connection.setDoInput(true);
//Connected to server
connection.connect();
//downloading image
InputStream input = connection.getInputStream();
//converting image to bitmap
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
if (result != null) {
result = mBitmap;
new ImageServer(mContext).save(result);
}
}
}
EDIT :
Tried to use picasso :
#Override
protected void onPostExecute(JSONObject response) {
super.onPostExecute(response);
count=0;
if (response.has("message")) {
JSONObject userJson = null;
String message = null;
count++;
try {
if (response.getString("message").equalsIgnoreCase(KEY_SUCCESS)) {
Toast.makeText(mContext, "user authenticated successfully", Toast.LENGTH_LONG).show();
userJson = response.getJSONObject("user");
String userId = userJson.getString("user_id");
String userName = userJson.getString("user_name");
String profileImage = userJson.getString("profile_image");
String mobileNo = userJson.getString("mobile_no");
String url = ServiceUrl.getBaseUrl() + ServiceUrl.getImageUserUrl() + profileImage;
Log.e("url", url);
User user = new User();
user.setmUserId(userId);
user.setmUserName(userName);
user.setmProfileImage(profileImage);
user.setmMobileNo(mobileNo);
SharedPreferences.Editor editor = mContext.getSharedPreferences("username",mContext.MODE_PRIVATE).edit();
editor.putString("UserUsername",userName);
editor.commit();
Target target = new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
try {
File f = new File(mContext.getCacheDir(), "Profile");
f.createNewFile();
//Convert bitmap to byte array
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 0 /*ignored for PNG*/, bos);
byte[] bitmapdata = bos.toByteArray();
//write the bytes in file
FileOutputStream fos = new FileOutputStream(f);
fos.write(bitmapdata);
fos.flush();
fos.close();
Log.e("File",String.valueOf(f));
}
catch (IOException e)
{
}
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
};
Picasso.with(mContext).load(url).into(target);
Toast.makeText(mContext, "user authenticated successfully", Toast.LENGTH_LONG).show();
progressDialog.dismiss();
mContext.startActivity(intent);
Picasso.with(mContext).cancelRequest(target);
}
}
What's going wrong?
Try this I am getting image by this method.
URL url1l = new URL("<Image url>");
URLConnection connection = url1l.openConnection();
connection.connect();
// this will be useful so that you can show a typical 0-100% progress bar
int fileLength = connection.getContentLength();
// download the file
InputStream is = new BufferedInputStream(connection.getInputStream());
bitmap = BitmapFactory.decodeStream(is);
The most likely reason is that you are getting an error from the server or that the data you are getting back cannot be decoded. First of all, check the response code after the connection is opened:
connection.connect();
int respCode = connection.getResponseCode();
Log.d("resp code", "response code " + respCode);
If you get anything other than 200, then something is wrong with retrieving data (wrong url, auth, or server error). If you do get 200, then the issue is with the data you are receiving. Read the data into a byte array and dump it into a file to examine.
First check with image is really exists or not as #aman grover said
if available use Picasso Lib to download image and from url.
here is sample code
private Target target = new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
//Note : here you can get Bitmap
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
}
private void someMethod() {
Picasso.with(this).load("url").into(target);
}
#Override
public void onDestroy() { // could be in onPause or onStop
Picasso.with(this).cancelRequest(target);
super.onDestroy();
}

Uploading image to mysql database through android

Hello before someone says that i shouldnt store in database as blob, well i need it i have my reasons. Last time i asked this only response i got was like dont store in database or something. Well here is my code thatone part works the other part doesnt works, the part that works is taking photo and displaying it in imageview , not working is uploading to mysql database. If more information is needed tell me i will edit answer. thank you in advance.
Code
Activity:
public class takefoto extends BaseNavegationActivity {
Button takebt, sendbt;
String ba1;
String mCurrentPhotoPath;
ImageView mFoto;
int CodServico;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.takefoto);
takebt = (Button) findViewById(R.id.takebt);
mFoto = (ImageView) findViewById(R.id.fotoser);
takebt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
captureImage();
}
});
sendbt = (Button) findViewById(R.id.sendbt);
sendbt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
upload();
}
});
Bundle extras = getIntent().getExtras();
CodServico=extras.getInt("CodServico");
Log.i("CODSERVICO",CodServico+"");
}
private void upload() {
Bitmap bm = BitmapFactory.decodeFile(mCurrentPhotoPath);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 50, bao);
byte[] ba = bao.toByteArray();
ba1 = Base64.encodeToString(ba,Base64.DEFAULT);
// Upload image to server
ServerRequests serverRequests = new ServerRequests(takefoto.this);
serverRequests.storeFotoDataInBackground(ba1, CodServico, new GetUpdaterCallBack() {
#Override
public void done(String returnUser) {
if (returnUser.equalsIgnoreCase("sucesso")) {
Toast.makeText(getApplicationContext(),"Enviado!",Toast.LENGTH_SHORT).show();
} else{
showError();
}
}
});
}
private void captureImage() {
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
ex.printStackTrace();
}
// Continue only if the File was successfully created
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
startActivityForResult(takePictureIntent, 100);
}
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 100 && resultCode == RESULT_OK) {
setPic();
}
}
private void setPic() {
// Get the dimensions of the View
int targetW = mFoto.getWidth();
int targetH = mFoto.getHeight();
// Get the dimensions of the bitmap
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
// Determine how much to scale down the image
int scaleFactor = Math.min(photoW / targetW, photoH / targetH);
// Decode the image file into a Bitmap sized to fill the View
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bmOptions.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
mFoto.setImageBitmap(bitmap);
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
Log.e("Getpath", "Cool" + mCurrentPhotoPath);
return image;
}
private void showError(){
android.app.AlertDialog.Builder dialogBuilder=new android.app.AlertDialog.Builder(getBaseContext());
dialogBuilder.setMessage("Ocorreu um erro, por favor tente novamente mais tarde.");
dialogBuilder.setPositiveButton("Ok", null);
dialogBuilder.show();
}
}
ServerResquest method:
public void storeFotoDataInBackground(String ba, int codservico,GetUpdaterCallBack userCallback){
progressDialog.show();
new StoreFotoDataAsyncTasck(ba, codservico, userCallback).execute();
}
public class StoreFotoDataAsyncTasck extends AsyncTask<Void, Void, String> {
String ba;
int CodServico;
GetUpdaterCallBack registerCallback;
public StoreFotoDataAsyncTasck(String ba1, int codservico,GetUpdaterCallBack registerCallback) {
this.ba = ba1;
this.CodServico=codservico;
this.registerCallback = registerCallback;
}
#Override
protected String doInBackground(Void... params) {
String retorno = null;
try {
URL url = new URL(SERVER_ADDRESS + "myphpfile.php");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
Uri.Builder builder = new Uri.Builder()
.appendQueryParameter("CodServico", this.CodServico+"")
.appendQueryParameter("Imagem", this.ba);
Log.i("IMAGEM",this.ba+" CodServico"+this.CodServico);
final String postParameters = builder.build().getEncodedQuery();
conn.setConnectTimeout(3000);
conn.setReadTimeout(3000);
conn.setRequestMethod("POST");
conn.setFixedLengthStreamingMode(postParameters.getBytes().length);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setDoInput(true);
conn.setDoOutput(true);
//send the POST out
PrintWriter pw = new PrintWriter(conn.getOutputStream());
pw.print(postParameters);
pw.close();
conn.connect();
String result = convertStreamToString(conn.getInputStream());
JSONObject jObject = new JSONObject(result);
if(jObject.length()!=0){
retorno= jObject.getString("estado");
}
} catch (Exception e) {
e.printStackTrace();
}
return retorno;
}
}
My php code:
<?php
$codservic=$_POST['CodServico'];
$image = $_POST['Imagem'];
$con = mysqli_connect("xxxxxxxxx","xxxxxxxx","xxxxxxxxx","xxxxxxxxxx") or die('Unable To connect');
$sql = "insert into xxxxxxxx (xxxxxxxx,xxxxxxxx) values(?,?)";
$stmt = mysqli_prepare($con,$sql);
mysqli_stmt_bind_param($stmt,"is",$codservic,$image);
$sucesso=mysqli_stmt_execute($stmt);
if($sucesso){
$estado = array();
$estado[estado] = "sucesso";
echo json_encode($estado);
}
?>
Well after lot's of search i got it finnaly to work for those who need it too i will post my code.
Main activity:
public class takefoto extends BaseNavegationActivity {
Button takebt, sendbt;
String ba1;
String mCurrentPhotoPath;
ImageView mFoto;
int CodServico;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.takefoto);
takebt = (Button) findViewById(R.id.takebt);
mFoto = (ImageView) findViewById(R.id.fotoser);
takebt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
captureImage();
}
});
sendbt = (Button) findViewById(R.id.sendbt);
sendbt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
upload();
}
});
Bundle extras = getIntent().getExtras();
CodServico=extras.getInt("CodServico");
Log.i("CODSERVICO",CodServico+"");
}
private void upload() {
Bitmap bm = BitmapFactory.decodeFile(mCurrentPhotoPath);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 50, bao);
byte[] ba = bao.toByteArray();
Log.i("IMAGEM NAO CONVERTIDA",ba+"");
ba1 = Base64.encodeToString(ba,Base64.DEFAULT);
// Get image and
// Upload image to server
ServerRequests serverRequests = new ServerRequests(takefoto.this);
serverRequests.storeFotoDataInBackground(ba1, CodServico, new GetUpdaterCallBack() {
#Override
public void done(String returnUser) {
if (returnUser.equalsIgnoreCase("sucesso")) {
Toast.makeText(getApplicationContext(),"Enviado!",Toast.LENGTH_SHORT).show();
} else{
showError();
}
}
});
}
private void captureImage() {
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
ex.printStackTrace();
}
// Continue only if the File was successfully created
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
startActivityForResult(takePictureIntent, 100);
}
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 100 && resultCode == RESULT_OK) {
setPic();
}
}
private void setPic() {
// Get the dimensions of the View
int targetW = mFoto.getWidth();
int targetH = mFoto.getHeight();
// Get the dimensions of the bitmap
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
// Determine how much to scale down the image
int scaleFactor = Math.min(photoW / targetW, photoH / targetH);
// Decode the image file into a Bitmap sized to fill the View
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bmOptions.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
mFoto.setImageBitmap(bitmap);
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
Log.e("Getpath", "Cool" + mCurrentPhotoPath);
return image;
}
private void showError(){
android.app.AlertDialog.Builder dialogBuilder=new android.app.AlertDialog.Builder(getBaseContext());
dialogBuilder.setMessage("Ocorreu um erro, por favor tente novamente mais tarde.");
dialogBuilder.setPositiveButton("Ok", null);
dialogBuilder.show();
}
}
Server requests method(the part of the insert with database):
#Override
protected String doInBackground(Void... params) {
String retorno = null;
try {
URL url = new URL(SERVER_ADDRESS + "yourphpfile.php");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
Uri.Builder builder = new Uri.Builder()
.appendQueryParameter("Value1", this.CodServico+"")
.appendQueryParameter("Image", this.ba);
Log.i("IMAGEM",""+this.ba);
final String postParameters = builder.build().getEncodedQuery();
conn.setConnectTimeout(3000);
conn.setReadTimeout(3000);
conn.setRequestMethod("POST");
conn.setFixedLengthStreamingMode(postParameters.getBytes().length);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setDoInput(true);
conn.setDoOutput(true);
//send the POST out
PrintWriter pw = new PrintWriter(conn.getOutputStream());
pw.print(postParameters);
pw.close();
conn.connect();
String result = convertStreamToString(conn.getInputStream());
JSONObject jObject = new JSONObject(result);
if(jObject.length()!=0){
retorno= jObject.getString("status");// if was sucess or not
}
} catch (Exception e) {
e.printStackTrace();
}
return retorno;
}
My php code:
<?php
$codservic=$_POST['Value1'];
$image = $_POST['Image'];
header("Content-type: image/jpg");
$img = base64_decode($image);
$con = mysqli_connect("your connection string") or die('Unable To connect');
$sql = "insert into yourtable (yourcamp1,image) values(?,?)";
$stmt = mysqli_prepare($con,$sql);
mysqli_stmt_bind_param($stmt,"is",$codservic,$img);
$sucesso=mysqli_stmt_execute($stmt);
$estado = array();
if($sucesso){
$estado[status] = "sucess";
echo json_encode($estado);
} else {
$estado[status] = "error";
echo json_encode($estado);
}
?>

Categories

Resources