Я пытаюсь сделать снимок на камеру Android и загрузить путь к нему на сервер MySQL, а также сохранить файл изображения в локальной папке. Но файл изображения, сгенерированный в локальной папке, всегда пуст и имеет размер всего 1 КБ.
Программа генерирует пустой файл изображения
Это мой метод onCreate ():
ImageViewHolder = findViewById(R.id.imageViewProduk);
CaptureImageFromCamera = findViewById(R.id.BtnCameraProduk);
EnableRuntimePermissionToAccessCamera();
CaptureImageFromCamera.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)
{
requestPermissions(new String[]{Manifest.permission.CAMERA}, 7);
intentCam = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intentCam, 7);
}
else
{
intentCam = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intentCam, 7);
}
}
});
Это onActivityResult ():
protected void onActivityResult(int requestCode, int resultCode, Intent intentCam) {
super.onActivityResult(requestCode, resultCode, intentCam);
if(resultCode != RESULT_CANCELED){
if (requestCode == 7) {
bitmap = (Bitmap) intentCam.getExtras().get("data");
ImageViewHolder.setImageBitmap(bitmap);
}
}
}
Это функция для предоставления доступа к камере:
public void EnableRuntimePermissionToAccessCamera(){
if (ActivityCompat.shouldShowRequestPermissionRationale(Detail_Produk.this,
Manifest.permission.CAMERA))
{
// Printing toast message after enabling runtime permission.
Toast.makeText(Detail_Produk.this,"CAMERA permission allows us to Access CAMERA app",
Toast.LENGTH_LONG).show();
} else {
ActivityCompat.requestPermissions(Detail_Produk.this,new String[]{Manifest.permission.CAMERA},
RequestPermissionCode);
}
}
Затем, когда я закончу захват изображения, я вызываю функцию ImageUploadToServerFunction ( ) функция:
public void ImageUploadToServerFunction(){
ByteArrayOutputStream byteArrayOutputStreamObject;
byteArrayOutputStreamObject = new ByteArrayOutputStream();
// Converting bitmap image to jpeg format, so by default image will upload in jpeg format.
//bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStreamObject);
byte[] byteArrayVar = byteArrayOutputStreamObject.toByteArray();
final String ConvertImage = Base64.encodeToString(byteArrayVar, Base64.DEFAULT);
class AsyncTaskUploadClass extends AsyncTask<Void,Void,String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog at image upload time.
progressDialog = ProgressDialog.show(Detail_Produk.this,
"Image is Uploading","Please Wait",false,false);
}
@Override
protected void onPostExecute(String string1) {
super.onPostExecute(string1);
// Dismiss the progress dialog after done uploading.
progressDialog.dismiss();
// Printing uploading success message coming from server on android app.
Toast.makeText(Detail_Produk.this,string1 + "Success~",Toast.LENGTH_LONG).show();
// Setting image as transparent after done uploading.
ImageViewHolder.setImageResource(android.R.color.transparent);
}
@Override
protected String doInBackground(Void... params) {
ImageProcessClass imageProcessClass = new ImageProcessClass();
HashMap<String,String> HashMapParams = new HashMap<String,String>();
HashMapParams.put(ImagePathFieldOnServer, ConvertImage);
String FinalData = imageProcessClass.ImageHttpRequest(ImageUploadPathOnSever, HashMapParams);
return FinalData;
}
}
AsyncTaskUploadClass AsyncTaskUploadClassOBJ = new AsyncTaskUploadClass();
AsyncTaskUploadClassOBJ.execute();
}
И, наконец, это ImageProcessClass ():
public class ImageProcessClass{
public String ImageHttpRequest(String requestURL,HashMap<String, String> PData) {
StringBuilder stringBuilder = new StringBuilder();
try {
URL url;
HttpURLConnection httpURLConnectionObject ;
OutputStream OutPutStream;
BufferedWriter bufferedWriterObject ;
BufferedReader bufferedReaderObject ;
int RC ;
url = new URL(requestURL);
httpURLConnectionObject = (HttpURLConnection) url.openConnection();
httpURLConnectionObject.setReadTimeout(19000);
httpURLConnectionObject.setConnectTimeout(19000);
httpURLConnectionObject.setRequestMethod("insert");
httpURLConnectionObject.setDoInput(true);
httpURLConnectionObject.setDoOutput(true);
OutPutStream = httpURLConnectionObject.getOutputStream();
bufferedWriterObject = new BufferedWriter(
new OutputStreamWriter(OutPutStream, "UTF-8"));
bufferedWriterObject.write(bufferedWriterDataFN(PData));
bufferedWriterObject.flush();
bufferedWriterObject.close();
OutPutStream.close();
RC = httpURLConnectionObject.getResponseCode();
if (RC == HttpsURLConnection.HTTP_OK) {
bufferedReaderObject = new BufferedReader
(new InputStreamReader(httpURLConnectionObject.getInputStream()));
stringBuilder = new StringBuilder();
String RC2;
while ((RC2 = bufferedReaderObject.readLine()) != null){
stringBuilder.append(RC2);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return stringBuilder.toString();
}