I get capture image from android camera. Then save in sd card folder which is name Test_Folder. Then i do try to convert Image into Encode String via Base64. Then i get string. When getting encoded codes Base 64 Encoder / Decoder website. Get i download image from this website. Finally I get black image always.
My codes below step by step: such as
MainActivity.java
public class MainActivity extends Activity {
public String imageName, imagePath;
public static final String TAG = "MainActivity";
protected static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 0;
public File dir;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dir = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/" + "Test_Folder");
if (dir.exists()) {
Log.i(TAG, "folder already exist");
} else {
if (dir.mkdirs()) {
Log.i(TAG, "folder make now");
}
}
SecureRandom random = new SecureRandom();
String randomName = new BigInteger(10, random).toString(4);
imageName = "myImage" + "" + randomName + ".PNG";
File file = new File(dir, imageName);
imagePath = file.getAbsolutePath();
Uri outputFileUri = Uri.fromFile(file);
Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
i.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(i, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
File file = new File(dir, imageName);
String imageRowData = imageToBinary(file);
Log.i(TAG, "::image::" + imageRowData);
Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
if (bitmap.getWidth() > bitmap.getHeight()) {
// force to resize given values
// getScaledBitMap(imagePath, 2048, 1536);
// Toast.makeText(getApplicationContext(), "Landscape",
// Toast.LENGTH_LONG).show();
} else {
// force to resize given values
// getScaledBitMap(imagePath, 1536, 2048);
// Toast.makeText(getApplicationContext(), "portrait",
// Toast.LENGTH_LONG).show();
}
} else if (resultCode == RESULT_CANCELED) {
// user cancelled Image capture
Toast.makeText(getApplicationContext(),
"User cancelled image capture", Toast.LENGTH_SHORT)
.show();
} else {
// failed to capture image
Toast.makeText(getApplicationContext(),
"Sorry! Failed to capture image", Toast.LENGTH_SHORT)
.show();
}
} else {
//
}
}
public String imageToBinary(File imgFile) {
// image-> bitmap
BitmapFactory.Options option = new BitmapFactory.Options();
option.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bm = BitmapFactory.decodeFile(imgFile.getPath(), option);
// bitmap-> bytearrayoutputstream
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Log.i("DDDDDDDDDDDDDDD", "DDDDDDDDDDDDDDDDDDDDDD");
bm.compress(Bitmap.CompressFormat.PNG, 90, baos);
Log.i("FFFFFFFFFFFFFFFFFff", "FFFFFFFFFFFFFFF");
// bytearrayoutputstream-> byte[]
byte[] ba = baos.toByteArray();
// byte[]-> string
String imageBinary = Base64.encodeBytes(ba);
return imageBinary;
}
// ----------------------------Start of resizing image
// codes------------------------
private Bitmap getScaledBitMap(String filePath, int reqWidth, int reqHeight) {
if (filePath != null && filePath.contains("file")) {
filePath = filePath.replace("file://", "");
}
Log.i(TAG, ":test:0");
Bitmap unscaledBitmap = ScalingUtilities.decodeBitmap(getResources(),
filePath, reqWidth, reqHeight, ScalingLogic.CROP);
// Part 2: Scale image
Bitmap scaledBitmap = ScalingUtilities.createScaledBitmap(
unscaledBitmap, reqWidth, reqHeight, ScalingLogic.CROP);
Log.i(TAG, ":test:1");
unscaledBitmap.recycle();
Log.i(TAG, ":test:2");
// convert and save sd card folder
try {
Log.i(TAG, ":test:try");
OutputStream fOut = null;
File file = new File(dir, imageName);
fOut = new FileOutputStream(file);
scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
fOut.flush();
fOut.close();
fOut = null;
MediaStore.Images.Media.insertImage(getContentResolver(),
file.getAbsolutePath(), file.getName(), file.getName());
String imageRowData = imageToBinary(file);
Log.i(TAG, ":imageRowData:" + imageRowData);
} catch (FileNotFoundException e) {
Log.i(TAG, ":test:FileNotFoundException:" + e.toString());
e.printStackTrace();
} catch (IOException e) {
Log.i(TAG, ":test:IOException:" + e.toString());
e.printStackTrace();
}
return scaledBitmap;
}
private static int exifToDegrees(int exifOrientation) {
if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_90) {
return 90;
} else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_180) {
return 180;
} else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_270) {
return 270;
}
return 0;
}
public static class ScalingUtilities {
/**
* Utility function for decoding an image resource. The decoded bitmap
* will be optimized for further scaling to the requested destination
* dimensions and scaling logic.
*
* @param res
* The resources object containing the image data
* @param resId
* The resource id of the image data
* @param dstWidth
* Width of destination area
* @param dstHeight
* Height of destination area
* @param scalingLogic
* Logic to use to avoid image stretching
* @return Decoded bitmap
*/
public static Bitmap decodeBitmap(Resources res, String pathName,
int dstWidth, int dstHeight, ScalingLogic scalingLogic) {
Options options = new Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(pathName, options);
options.inJustDecodeBounds = false;
options.inSampleSize = calculateSampleSize(options.outWidth,
options.outHeight, dstWidth, dstHeight, scalingLogic);
Bitmap unscaledBitmap = BitmapFactory.decodeFile(pathName, options);
return unscaledBitmap;
}
/**
* Utility function for creating a scaled version of an existing bitmap
*
* @param unscaledBitmap
* Bitmap to scale
* @param dstWidth
* Wanted width of destination bitmap
* @param dstHeight
* Wanted height of destination bitmap
* @param scalingLogic
* Logic to use to avoid image stretching
* @return New scaled bitmap object
*/
public static Bitmap createScaledBitmap(Bitmap unscaledBitmap,
int dstWidth, int dstHeight, ScalingLogic scalingLogic) {
Rect srcRect = calculateSrcRect(unscaledBitmap.getWidth(),
unscaledBitmap.getHeight(), dstWidth, dstHeight,
scalingLogic);
Rect dstRect = calculateDstRect(unscaledBitmap.getWidth(),
unscaledBitmap.getHeight(), dstWidth, dstHeight,
scalingLogic);
Bitmap scaledBitmap = Bitmap.createBitmap(dstRect.width(),
dstRect.height(), Config.ARGB_8888);
Canvas canvas = new Canvas(scaledBitmap);
canvas.drawBitmap(unscaledBitmap, srcRect, dstRect, new Paint(
Paint.FILTER_BITMAP_FLAG));
return scaledBitmap;
}
/**
* ScalingLogic defines how scaling should be carried out if source and
* destination image has different aspect ratio.
*
* CROP: Scales the image the minimum amount while making sure that at
* least one of the two dimensions fit inside the requested destination
* area. Parts of the source image will be cropped to realize this.
*
* FIT: Scales the image the minimum amount while making sure both
* dimensions fit inside the requested destination area. The resulting
* destination dimensions might be adjusted to a smaller size than
* requested.
*/
public static enum ScalingLogic {
CROP, FIT
}
/**
* Calculate optimal down-sampling factor given the dimensions of a
* source image, the dimensions of a destination area and a scaling
* logic.
*
* @param srcWidth
* Width of source image
* @param srcHeight
* Height of source image
* @param dstWidth
* Width of destination area
* @param dstHeight
* Height of destination area
* @param scalingLogic
* Logic to use to avoid image stretching
* @return Optimal down scaling sample size for decoding
*/
public static int calculateSampleSize(int srcWidth, int srcHeight,
int dstWidth, int dstHeight, ScalingLogic scalingLogic) {
if (scalingLogic == ScalingLogic.FIT) {
final float srcAspect = (float) srcWidth / (float) srcHeight;
final float dstAspect = (float) dstWidth / (float) dstHeight;
if (srcAspect > dstAspect) {
return srcWidth / dstWidth;
} else {
return srcHeight / dstHeight;
}
} else {
final float srcAspect = (float) srcWidth / (float) srcHeight;
final float dstAspect = (float) dstWidth / (float) dstHeight;
if (srcAspect > dstAspect) {
return srcHeight / dstHeight;
} else {
return srcWidth / dstWidth;
}
}
}
/**
* Calculates source rectangle for scaling bitmap
*
* @param srcWidth
* Width of source image
* @param srcHeight
* Height of source image
* @param dstWidth
* Width of destination area
* @param dstHeight
* Height of destination area
* @param scalingLogic
* Logic to use to avoid image stretching
* @return Optimal source rectangle
*/
public static Rect calculateSrcRect(int srcWidth, int srcHeight,
int dstWidth, int dstHeight, ScalingLogic scalingLogic) {
if (scalingLogic == ScalingLogic.CROP) {
final float srcAspect = (float) srcWidth / (float) srcHeight;
final float dstAspect = (float) dstWidth / (float) dstHeight;
if (srcAspect > dstAspect) {
final int srcRectWidth = (int) (srcHeight * dstAspect);
final int srcRectLeft = (srcWidth - srcRectWidth) / 2;
return new Rect(srcRectLeft, 0, srcRectLeft + srcRectWidth,
srcHeight);
} else {
final int srcRectHeight = (int) (srcWidth / dstAspect);
final int scrRectTop = (int) (srcHeight - srcRectHeight) / 2;
return new Rect(0, scrRectTop, srcWidth, scrRectTop
+ srcRectHeight);
}
} else {
return new Rect(0, 0, srcWidth, srcHeight);
}
}
/**
* Calculates destination rectangle for scaling bitmap
*
* @param srcWidth
* Width of source image
* @param srcHeight
* Height of source image
* @param dstWidth
* Width of destination area
* @param dstHeight
* Height of destination area
* @param scalingLogic
* Logic to use to avoid image stretching
* @return Optimal destination rectangle
*/
public static Rect calculateDstRect(int srcWidth, int srcHeight,
int dstWidth, int dstHeight, ScalingLogic scalingLogic) {
if (scalingLogic == ScalingLogic.FIT) {
final float srcAspect = (float) srcWidth / (float) srcHeight;
final float dstAspect = (float) dstWidth / (float) dstHeight;
if (srcAspect > dstAspect) {
return new Rect(0, 0, dstWidth,
(int) (dstWidth / srcAspect));
} else {
return new Rect(0, 0, (int) (dstHeight * srcAspect),
dstHeight);
}
} else {
return new Rect(0, 0, dstWidth, dstHeight);
}
}
}
// ---------end of resizing image codes------------------------
}
My Base64.java Base64.java
also i add permission in AndroidMenifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
can you anybody help me getting original image giving modification or helpful links of example or tutorial or others?
You can try like this. Such as:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Bitmap bm = BitmapFactory.decodeFile(imagePath);
bm.compress(Bitmap.CompressFormat.JPEG, 90, baos);
byte[] byteImage_photo = baos.toByteArray();
Log.i("BM Size:", " Byte Count: " + bm.getByteCount());
Log.i("baos Size:", " Size: " + baos.size());
Log.i("Byte Image photo:", " Image photo Size: "
+ byteImage_photo.length);
String imageRowData = Base64.encodeToString(byteImage_photo,
Base64.DEFAULT);
File file = new File(dir, "/filename.txt");
if (!file.exists())
file.createNewFile();
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(imageRowData);
bw.close();
I expect it to be helpful, Hopefully