Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/206.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在android中,当图像二进制文件来自编码二进制(字符串)时,为什么图像总是黑色?_Android_Encoding_Decode_Android Image - Fatal编程技术网

在android中,当图像二进制文件来自编码二进制(字符串)时,为什么图像总是黑色?

在android中,当图像二进制文件来自编码二进制(字符串)时,为什么图像总是黑色?,android,encoding,decode,android-image,Android,Encoding,Decode,Android Image,我从安卓摄像头获取拍摄图像。然后保存在sd卡文件夹中,即名称Test_文件夹中。然后我尝试通过Base64将图像转换为编码字符串。然后我得到绳子。获取编码代码时。从这个网站下载图片。最后,我总是得到黑色的图像 我的代码如下逐步:如 MainActivity.java public class MainActivity extends Activity { public String imageName, imagePath; public static final Str

我从安卓摄像头获取拍摄图像。然后保存在sd卡文件夹中,即名称Test_文件夹中。然后我尝试通过Base64将图像转换为编码字符串。然后我得到绳子。获取编码代码时。从这个网站下载图片。最后,我总是得到黑色的图像

我的代码如下逐步:如

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------------------------

}
我的Base64.java

我还在AndroidMenifest.xml中添加了权限

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>


你们有谁能帮我得到原始图像,给修改或有用的链接的例子,教程或其他

你可以这样试试。例如:

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();

我希望它会有所帮助,希望

为什么不使用
android.util.Base64
class?@kablu您能尝试将代码列表减少到,以便更好地解决问题吗?或者,描述该问题可能发生在例如
imageToBinary
方法中。该问题是否涉及
ScaleUtilities
类?如果缩放不影响问题,请删除对实用程序类的调用,并删除实用程序类。