Home > Software engineering >  android saves image not correctly
android saves image not correctly

Time:08-27

I'm trying to save the image to my phone's internal storage. After trying several ways to save files, I managed to save the photo, but it does not open on the phone itself. I can find this photo in the phone's internal storage and open it (android recognizes the file as a photo since it automatically opens it in the gallery), but the photo is not displayed.

When open the photo, I see the following: photo In the phone, this photo takes 0 kilobytes.

My function is to save a photo to an internal storage:

    fun saveImageToStorage(urlImage: String, pathTitle: String) : String{
        val dirs = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES)
        val dir = File(dirs?.absolutePath, pathTitle)
        if(!dir.exists()){
            dir.mkdir()
        }

        val file = File(dir, System.currentTimeMillis().toString()   ".jpg")
        val bitmap: Bitmap = downloadImage(urlImage)

        try {
            file.createNewFile()
            val imageStream = ByteArrayOutputStream()
            bitmap.compress(Bitmap.CompressFormat.JPEG, 80, imageStream)

            val image = imageStream.toByteArray()
            Log.i("IMAGE SIZE", "${image.size}")
            imageStream.write(image)
            imageStream.flush()
            imageStream.close()

        }catch (e: Exception){
            e.message
        }

        Log.i("INFOOOOOO", file.absolutePath)
        return file.absolutePath
    }

Upload an image and get a bitmap.

    fun downloadImage(urlImage: String): Bitmap {
        return Glide
            .with(context)
            .asBitmap()
            .timeout(60_000)
            .load(urlImage)
            .fitCenter()
            .submit()
            .get()
    }

I've connected the dependencies

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

My instrumental test in which I try to perform it. It is located in "src/AndroidTest"

    @Test
    fun saveAdnGetPhoto(){
        val path = daoAdapter.saveImageToExternalStorage("https://www.gstatic.com/youtube/src/web/htdocs/img/tv_stack.png", "Naruto")

        Awaitility.await().atMost(2, TimeUnit.SECONDS).untilAsserted {
            val output = daoAdapter.getPhotoFromStorage(path)
            assertEquals(true, output != null)
        }
    }

Error when trying to get a photo along the saved path

java.io.FileNotFoundException: /storage/emulated/0/Android/data/com.example.mangaua/files/Pictures/Naruto/1661511946507.jpg
at android.content.res.AssetManager.openAsset(Native Method)
at android.content.res.AssetManager.open(AssetManager.java:690)
at android.content.res.AssetManager.open(AssetManager.java:664)
at com.example.mangaua.menu.connector.DownloadPageChapter.getPhoto(DownloadPageChapter.kt:95)
at com.example.mangaua.menu.connector.ConnectorBaseAndParse.getPhotoFromStorage(ConnectorBaseAndParse.kt:443)
at com.example.mangaua.TestDownloadAndSaveImageToExternal.saveAdnGetPhoto$lambda-0(TestDownloadAndSaveImageToExternal.kt:72)
at com.example.mangaua.TestDownloadAndSaveImageToExternal.$r8$lambda$jm-yYcWapmPfDqI53v3Npy212R8(Unknown Source:0)
at com.example.mangaua.TestDownloadAndSaveImageToExternal$$ExternalSyntheticLambda0.run(Unknown Source:4)
at org.awaitility.core.AssertionCondition$1.eval(AssertionCondition.java:55)
at org.awaitility.core.ConditionAwaiter$ConditionPoller.call(ConditionAwaiter.java:201)
at org.awaitility.core.ConditionAwaiter$ConditionPoller.call(ConditionAwaiter.java:188)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
at java.lang.Thread.run(Thread.java:784)

Function for returning photos

    fun getPhoto(pathImage: String) : Bitmap{
        return BitmapFactory.decodeStream(InstrumentationRegistry.getInstrumentation().context.assets.open(pathImage))
    }

Debug mode

  1. Download photo
  2. ByteArrayOutputStream to byteArray
  3. Write image

thanks for your answers, I usually don't like to create themes on stack overflow due to my mistakes as I always found the answer but this time I'm trampling on one place around Sunday.

CodePudding user response:

I think you can use FileOutputStream instead of ByteArrayOutputStream.

  • Related