App says Image Downloaded Successfully but no image shows up in gallery - java

The app gets the image from the given URL and displays the image and on clicking the download button, it says that the image has been downloaded successfully but there is no image in the gallery. Can someone tell me how I can fix this?
This is my Image View and Download activity. I have also added proper permissions to the Android Manifest.
private Button btnImageDownload;
private ProgressDialog pd;
private ImageView viewDownloadImage;
private Images imageId;
private File folderName;
private String imageName;
private Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
if (msg.what == 1) {
if (pd != null) {
pd.dismiss();
}
Utils.showNetworkAlert(ImageViewAndDownload.this);
} else if (msg.what == 2) {
if (pd != null) {
pd.dismiss();
}
Utils.displayMessage("Image downloade succesfully",
ImageViewAndDownload.this);
// Media scaning
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://"
+ Environment.getExternalStorageDirectory())));
} else if (msg.what == 3) {
if (pd != null) {
pd.dismiss();
}
Utils.displayMessage("Image already downloaded ",
ImageViewAndDownload.this);
} else if (msg.what == 4) {
if (pd != null) {
pd.dismiss();
}
displayImageFromUrl((Bitmap) msg.obj);
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.imagedisplay);
viewDownloadImage = (ImageView) findViewById(R.id.viewImage);
btnImageDownload = (Button) findViewById(R.id.btnImageDownload);
imageId = new Images();
imageName = imageId.getImageId();
LoadImageFromWeb(Constant.IMAGE_BASE_URL + File.separator + imageName);
btnImageDownload.setOnClickListener(this);
}
public void onClick(View v) {
if (v == btnImageDownload) {
pd = ProgressDialog.show(ImageViewAndDownload.this, "",
"Downloading Image....", true, false);
new Thread(new Runnable() {
public void run() {
try {
String imageUrl = Constant.IMAGE_BASE_URL
+ File.separator + imageName;
String isDownloded = downloadImage(imageUrl, imageName);
if (isDownloded.equalsIgnoreCase("complete")) {
handler.sendEmptyMessage(2);
} else if (isDownloded.equalsIgnoreCase("")) {
handler.sendEmptyMessage(3);
} else {
handler.sendEmptyMessage(1);
}
} catch (Exception e) {
e.printStackTrace();
handler.sendEmptyMessage(1);
}
}
}).start();
}
}
// set display image to Imageview
public void displayImageFromUrl(Bitmap obj) {
viewDownloadImage.setImageBitmap(obj);
}
// image display from the webview
private void LoadImageFromWeb(final String url1) {
pd = ProgressDialog.show(ImageViewAndDownload.this, "",
"Loading Image....", true, false);
new Thread(new Runnable() {
public void run() {
try {
URL url = new URL(url1);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
InputStream is = connection.getInputStream();
Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(is, null, options);
if (options.outWidth > 3000 || options.outHeight > 2000) {
options.inSampleSize = 4;
} else if (options.outWidth > 2000
|| options.outHeight > 1500) {
options.inSampleSize = 3;
} else if (options.outWidth > 1000
|| options.outHeight > 1000) {
options.inSampleSize = 2;
}
// Do the actual decoding
options.inJustDecodeBounds = false;
is.close();
is = getHTTPConnectionInputStream(url1);
Bitmap myBitmap = BitmapFactory.decodeStream(is, null,
options);
is.close();
if (myBitmap != null) {
Message msg = new Message();
msg.obj = myBitmap;
msg.what = 4;
handler.sendMessage(msg);
} else {
handler.sendEmptyMessage(1);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
public InputStream getHTTPConnectionInputStream(String url1) {
URL url;
InputStream is = null;
try {
url = new URL(url1);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
is = connection.getInputStream();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return is;
}
// image download code
public String downloadImage(String imageDownloadUrl, String imageName) {
// create directory in SDCARD
if (android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED))
folderName = new File(Constant.STORE_IN_FOLDER);
else
folderName = getFilesDir();
if (!folderName.exists())
folderName.mkdirs();
String response = "";
// create file name and file.
File storeImageInSDCard = new File(folderName + File.separator
+ imageName);
if (!(storeImageInSDCard.exists() && storeImageInSDCard.length() > 0)) {
// start download image
response = downloadFile(imageDownloadUrl, imageName,
folderName.toString());
}
return response;
}
// start download image
public String downloadFile(final String url, final String name,
String foldername) {
File file;
FileOutputStream os = null;
Bitmap myBitmap;
try {
URL url1 = new URL(url.replaceAll(" ", "%20"));
System.out.println("Image url :::" + url1);
HttpURLConnection urlConnection = (HttpURLConnection) url1
.openConnection();
urlConnection.setDoOutput(false);
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// here create a file which define folder name and image name with
// extension.
file = new File(foldername, name + ".jpg");
InputStream inputStream = urlConnection.getInputStream();
byte[] buffer = new byte[1024];
int bufferLength = 0;
os = new FileOutputStream(file);
while ((bufferLength = inputStream.read(buffer)) > 0) {
os.write(buffer, 0, bufferLength);
}
os.flush();
os.close();
// if image size is too large we can scale image than download.
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
myBitmap = BitmapFactory
.decodeFile(file.getAbsolutePath(), options);
if (options.outWidth > 3000 || options.outHeight > 2000) {
options.inSampleSize = 4;
} else if (options.outWidth > 2000 || options.outHeight > 1500) {
options.inSampleSize = 3;
} else if (options.outWidth > 1000 || options.outHeight > 1000) {
options.inSampleSize = 2;
}
options.inJustDecodeBounds = false;
myBitmap = BitmapFactory
.decodeFile(file.getAbsolutePath(), options);
os = new FileOutputStream(file);
myBitmap.compress(CompressFormat.JPEG, 90, os);
os.flush();
os.close();
myBitmap.recycle();
return "complete";
} catch (SQLException e) {
e.printStackTrace();
return "error";
} catch (Exception e) {
e.printStackTrace();
return "error";
}
}
}

try this,
After saving the Image you have to use this
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri contentUri = Uri.fromFile(file);
mediaScanIntent.setData(contentUri);
getApplicationContext().sendBroadcast(mediaScanIntent);
you have to send a broadcast to System ,changes to reflect in the Gallery , so that you image will be shown in the gallery , if not , you have to restart Device for check the downloaded images..
hope it helps you..

I think you have to use Aquery for image download it is very Useful for image download from net.
Here the link for Aquery

Related

When i select image from recent then image is broken in android | Multiple images from recent

This error occurs mostly times when select images from recent folder
class com.bumptech.glide.load.engine.GlideException: Received null model
Call multiple images select
Sample Preview
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
i.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
*gallery*.launch(i);
gallery basically startActivityForResult(i,123) and OnActivityResult method is deprecated, the gallery is alternative which is defined below
ActivityResultLauncher<Intent> gallery = choosePhotoFromGallery();
and choosePhotoFromGallery() is method which is define below
private ActivityResultLauncher<Intent> choosePhotoFromGallery() {
return registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
result -> {
try {
if (result.getResultCode() == RESULT_OK) {
if (null != result.getData()) {
if (result.getData().getClipData() != null) {
ClipData mClipData = result.getData().getClipData();
for (int i = 0; i < mClipData.getItemCount(); i++) {
ClipData.Item item = mClipData.getItemAt(i);
Uri uri = item.getUri();
String imageFilePathColumn = getPathFromURI(this, uri);
productImagesList.add(imageFilePathColumn);
}
} else {
if (result.getData().getData() != null) {
Uri mImageUri = result.getData().getData();
String imageFilePathColumn = getPathFromURI(this, mImageUri);
productImagesList.add(imageFilePathColumn);
}
}
} else {
showToast(this, "You haven't picked Image");
productImagesList.clear();
}
} else {
productImagesList.clear();
}
} catch (Exception e) {
e.printStackTrace();
showToast(this, "Something went wrong");
productImagesList.clear();
}
});
}
and getPathFromURI() is method which define below
public String getPathFromURI(Context context, Uri contentUri) {
OutputStream out;
File file = getPath();
try {
if (file.createNewFile()) {
InputStream iStream = context != null ? context.getContentResolver().openInputStream(contentUri) : context.getContentResolver().openInputStream(contentUri);
byte[] inputData = getBytes(iStream);
out = new FileOutputStream(file);
out.write(inputData);
out.close();
return file.getAbsolutePath();
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private byte[] getBytes(InputStream inputStream) throws IOException {
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
return byteBuffer.toByteArray();
}
and the getPath() is
private File getPath() {
File folder = new File(Environment.getExternalStorageDirectory(), "Download");
if (!folder.exists()) {
folder.mkdir();
}
return new File(folder.getPath(), System.currentTimeMillis() + ".jpg");
}
THANK YOU IN ADVANCE HAPPY CODING

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

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);
}
?>

Difference between triggering camera.take picture from button click[Working] and through function call[Not working]

I am stuck at this. MY application clicks multiple images programmatically.
Issue is my take picture call is inside button listener click function.
1. When i do button click it triggers the thread for take picture that works.
2. If i directly call that obj.run() it does not-> shows take picture failed at run time.
3. If i do btn.perform click - still fails.
I am building an application that listens on a socket and on a trigger click multiple images n save them to create .gif.
code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// android.support.v7.appcompat.R.layout.activity_main;
setContentView(R.layout.activity_main);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
myContext = this;
initialize();
}
private int findFrontFacingCamera() {
int cameraId = -1;
// Search for the front facing camera
int numberOfCameras = Camera.getNumberOfCameras();
for (int i = 0; i < numberOfCameras; i++) {
CameraInfo info = new CameraInfo();
Camera.getCameraInfo(i, info);
if (info.facing == CameraInfo.CAMERA_FACING_FRONT) {
cameraId = i;
cameraFront = true;
break;
}
}
return cameraId;
}
private int findBackFacingCamera() {
int cameraId = -1;
//Search for the back facing camera
//get the number of cameras
int numberOfCameras = Camera.getNumberOfCameras();
//for every camera check
for (int i = 0; i < numberOfCameras; i++) {
CameraInfo info = new CameraInfo();
Camera.getCameraInfo(i, info);
if (info.facing == CameraInfo.CAMERA_FACING_BACK) {
cameraId = i;
cameraFront = false;
break;
}
}
return cameraId;
}
public void onResume() {
super.onResume();
if (!hasCamera(myContext)) {
Toast toast = Toast.makeText(myContext, "Sorry, your phone does not have a camera!", Toast.LENGTH_LONG);
toast.show();
finish();
}
if (mCamera == null) {
//if the front facing camera does not exist
if (findFrontFacingCamera() < 0) {
Toast.makeText(this, "No front facing camera found.", Toast.LENGTH_LONG).show();
switchCamera.setVisibility(View.GONE);
}
mCamera = Camera.open(findFrontFacingCamera());
// mCamera.Parameters.class.
mPicture = getPictureCallback();
mPreview.refreshCamera(mCamera);
capture.performClick();
Log.d("naval", "onresume- clicked performed");
}
}
public void initialize() {
cameraPreview = (LinearLayout) findViewById(R.id.camera_preview);
mPreview = new CameraPreview(myContext, mCamera);
cameraPreview.addView(mPreview);
capture = (Button) findViewById(R.id.button_capture);
// capture.setVisibility(View.GONE);
capture.setOnClickListener(captrureListener);
// capture.performClick();
switchCamera = (Button) findViewById(R.id.button_ChangeCamera);
switchCamera.setVisibility(View.GONE); // JUST CHANGE THIS TO MAKE SWITCH CAMERA WORKS
switchCamera.setOnClickListener(switchCameraListener);
Log.d("naval", "initialize");
}
OnClickListener switchCameraListener = new OnClickListener() {
#Override
public void onClick(View v) {
//get the number of cameras
int camerasNumber = Camera.getNumberOfCameras();
if (camerasNumber > 1) {
//release the old camera instance
//switch camera, from the front and the back and vice versa
releaseCamera();
chooseCamera();
} else {
Toast toast = Toast.makeText(myContext, "Sorry, your phone has only one camera!", Toast.LENGTH_LONG);
toast.show();
}
}
};
public void chooseCamera() {
//if the camera preview is the front
if (cameraFront) {
int cameraId = findBackFacingCamera();
if (cameraId >= 0) {
//open the backFacingCamera
//set a picture callback
//refresh the preview
mCamera = Camera.open(cameraId);
mPicture = getPictureCallback();
mPreview.refreshCamera(mCamera);
}
} else {
int cameraId = findFrontFacingCamera();
if (cameraId >= 0) {
//open the backFacingCamera
//set a picture callback
//refresh the preview
mCamera = Camera.open(cameraId);
mPicture = getPictureCallback();
mPreview.refreshCamera(mCamera);
}
}
}
#Override
protected void onPause() {
super.onPause();
//when on Pause, release camera in order to be used from other applications
releaseCamera();
Log.d("naval", "onpause");
}
private boolean hasCamera(Context context) {
//check if the device has camera
if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
return true;
} else {
return false;
}
}
private PictureCallback getPictureCallback() {
PictureCallback picture = new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
//make a new picture file
File pictureFile = getOutputMediaFile();
Log.d("naval", "picture call back start");
if (pictureFile == null) {
return;
}
try {
//write the file
FileOutputStream fos = new FileOutputStream(pictureFile);
Log.d("naval", "picture call back stream creation");
fos.write(data);
fos.close();
Toast toast = Toast.makeText(myContext, "Picture saved: " + pictureFile.getName(), Toast.LENGTH_LONG);
Log.d("naval", "picture call back toast");
toast.show();
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
//refresh camera to continue preview
mPreview.refreshCamera(mCamera);
//cameraPreview.start();
}
};
return picture;
}
OnClickListener captrureListener = new OnClickListener() {
#Override
public void onClick(View v) {
try {
Thread.sleep(1000);
}catch (Exception e)
{
e.printStackTrace();
}
CaptureThread captureThread = new CaptureThread();
captureThread.start();
/* String str = "";
while(true)
{
Log.d("naval","waiting for start inside file loop");
str = readFromFile();
if(str.equals("start")) {
Log.d("naval","calling capture object");
str = "";
CaptureThread captureThread = new CaptureThread();
captureThread.start();
}
else
{
try {
Log.d("naval","sleeping inside str loop");
Thread.sleep(1000);
}catch(Exception e)
{
e.printStackTrace();
}
continue;
// put sleep here
}
// read text file here at location /sdcard/info/info.txt
}*/
}
};
private String readFromFile() {
String ret = "";
try {
FileInputStream fis = new FileInputStream (new File("/storage/emulated/0/info/info.txt")); // 2nd line
// InputStream inputStream = openFileInput("/storage/emulated/0/info/info.txt");
if ( fis != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(fis);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString);
}
fis.close();
ret = stringBuilder.toString();
Log.d("naval- string",ret);
if(!ret.isEmpty())
{
Log.d("naval","str is not null");
//delete file or clear file and create one
File fil = new File("/storage/emulated/0/info/info.txt");
fil.delete();
// create
File file = new File("/storage/emulated/0/info/info.txt");
file.createNewFile();
}
}
}
catch (FileNotFoundException e) {
Log.e("login activity", "File not found: " + e.toString());
} catch (IOException e) {
Log.e("login activity", "Can not read file: " + e.toString());
}
return ret;
}
//make picture and save to a folder
private static File getOutputMediaFile() {
//make a new file directory inside the "sdcard" folder
File mediaStorageDir = new File("/sdcard/", "pics");
Log.d("naval", "save picture function");
//if this "JCGCamera folder does not exist
if (!mediaStorageDir.exists()) {
//if you cannot make this folder return
if (!mediaStorageDir.mkdirs()) {
return null;
}
}
Log.d("naval", "cave picture betweent");
//take the current timeStamp
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
//and make a media file:
mediaFile = new File(mediaStorageDir.getPath() + File.separator + "pic" + glo + ".png");
Log.d("naval", "File path above");
glo++;
return mediaFile;
}
private void releaseCamera() {
// stop and release camera
if (mCamera != null) {
mCamera.release();
mCamera = null;
}
}
class CaptureThread extends Thread {
#Override
public void run() {
int count = 0;
while(count < 6) {
**mCamera.takePicture(null, null, mPicture);**
count++;
try {
Thread.sleep(1000);
} catch (InterruptedException exception) {
exception.printStackTrace();
}
}
createGif();
}
public void createGif()
{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
AnimatedGifEncoder encoder = new AnimatedGifEncoder();
BitmapFactory.Options options=new BitmapFactory.Options();
options.inSampleSize = 6;
encoder.setDelay(100);
encoder.start(bos);
for(int i = 0;i<6;i++){
Bitmap bMap = BitmapFactory.decodeFile("/storage/emulated/0/pics/pic"+i+".png",options);
Log.d("naval","added image");
encoder.addFrame(bMap);
}
encoder.finish();
writeToFile(bos.toByteArray());
}
public void writeToFile(byte[] array) {
try {
String path = Environment.getExternalStorageDirectory() + "/gif/gif.gif";
FileOutputStream stream = new FileOutputStream(path);
stream.write(array);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
ok the answer is from button click it comes from UI thread. But the function call does not. to run this call the function from UI thread . It will work!!

download images from FTP :Caused by: java.lang.OutOfMemoryError

at com.example.newpingziyi.stir.CheckSdcard$LoadImagesFromSDCard.doInBackground(CheckSdcard.java:316)
error lines was make Stronger!
First.show that's error like java.lang.OutOfMemoryError!
this's code...
class LoadImagesFromSDCard extends AsyncTask<Object, LoadedImage, Object> {
#Override
protected Object doInBackground(Object... params) {
Bitmap newBitmap = null;
File file = new File(localPath);
String[] filepath = file.list();
for (String str : filepath) {
String filename = str;
String imagePath = localPath + "/" + filename;
File files = new File(imagePath);
FileInputStream is = null;
BufferedInputStream bis = null;
try {
is = new FileInputStream(new File(imagePath));
bis = new BufferedInputStream(is);
//this line was wrong!
Bitmap bitmap = BitmapFactory.decodeStream(bis);//this lines was wrong!!
is.close();
bis.close();
if (bitmap != null) {
newBitmap = Bitmap.createScaledBitmap(bitmap, 70, 70,
true);
bitmap.recycle();
if (newBitmap != null) {
publishProgress(new LoadedImage(newBitmap));
}
}
} catch (IOException e) {
}
}
return null;
}
#Override
public void onProgressUpdate(LoadedImage... value) {
addImage(value);
}
#Override
protected void onPostExecute(Object result) {
imageAdapter.notifyDataSetChanged();
}
}
Bitmap bitmap = BitmapFactory.decodeStream(bis);//this lines was wrong!!
now i make change below code.still OutOfMemoryError yet!
class LoadImagesFromSDCard extends AsyncTask<Object, LoadedImage, Object> {
#Override
protected Object doInBackground(Object... params) {
Bitmap newBitmap = null;
File file = new File(localPath);
String[] filepath = file.list();
for (String str : filepath) {
String filename = str;
String imagePath = localPath + "/" + filename;
File files = new File(imagePath);
FileInputStream is = null;
BufferedInputStream bis = null;
try {
is = new FileInputStream(new File(imagePath));
bis = new BufferedInputStream(is);
bis.mark(0);
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inJustDecodeBounds = true;
BitmapFactory.decodeStream(bis, null, opts);
int sizes = (opts.outWidth * opts.outHeight);
if (sizes > 1024 * 1024 * 4) {
int zoomRate = 2;
if (zoomRate <= 0)
zoomRate = 1;
opts.inSampleSize = zoomRate;
}
opts.inJustDecodeBounds = false;
bis.reset();
//this line was wrong!
Bitmap bitmap = BitmapFactory.decodeStream(bis, null, opts);//this lines was wrong!!
is.close();
bis.close();
if (bitmap != null) {
newBitmap = Bitmap.createScaledBitmap(bitmap, 70, 70,
true);
bitmap.recycle();
if (newBitmap != null) {
publishProgress(new LoadedImage(newBitmap));
}
}
} catch (IOException e) {
}
}
return null;
}
#Override
public void onProgressUpdate(LoadedImage... value) {
addImage(value);
}
#Override
protected void onPostExecute(Object result) {
imageAdapter.notifyDataSetChanged();
}
}
Bitmap bitmap = BitmapFactory.decodeStream(bis, null, opts);//this lines!
Here is my working code for downloading Bitmap, maybe it will help :
private Bitmap downloadBitmap(String url) {
// Getting the url from the html
url = url.substring(url.indexOf("src=\"") + 5, url.length() - 1);
url = url.substring(0, url.indexOf("\""));
final DefaultHttpClient client = new DefaultHttpClient();
final HttpGet getRequest = new HttpGet(url);
try {
HttpResponse response = client.execute(getRequest);
//check 200 OK for success
final int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Log.w("ImageDownloader", "Error " + statusCode +
" while retrieving bitmap from " + url);
return null;
}
final HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream inputStream = null;
try {
// getting contents from the stream
inputStream = entity.getContent();
// decoding stream data back into image Bitmap that android understands
final Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
} finally {
if (inputStream != null) {
inputStream.close();
}
entity.consumeContent();
}
}
} catch (Exception e) {
// You Could provide a more explicit error message for IOException
getRequest.abort();
Log.e("ImageDownloader", "Something went wrong while" +
" retrieving bitmap from " + url + e.toString());
}
return null;
}

Categories

Resources