Как уменьшить размер образа img
Перейти к содержимому

Как уменьшить размер образа img

  • автор:

Как уменьшить размер образа img

Обработка (распаковка и сборка) прошивок и образов (*.img, *.bin) строго под WINDOWS

Эта тема создана для продолжения обсуждения и помощи в обработке различных образов под Windows.

Полезное
(Примеры, варианты, утилиты, кухни, скрипты, обработки разных образов)

    — Программа распаковки и упаковки Android образов разделов (в том числе и распаковка super.img)

    + Подробности
    — Программа для распаковки SIN 3/4/5 образов

make_ext4fs — утилита для сборки образов в формате EXT4 и SPARSE EXT4 (добавлен способ сборки system через ‘таскание мышкой’)

AndImgTool (Android Image Tool)

Утилита для распаковки и обратной сборки загрузочных образов типа BOOT и RECOVERY для ARM-платформы, неважно какой проц устройства (рокчип, медиатек и т.д. и т.п.), важно какого стандарта придерживался производитель! На данный момент поддерживаются следующие форматы: Android Boot Image (так же и с оберткой MTK внутренних блоков кернела и рамдиска и с новым блоком DTB), KRNL Image, UBOOT Image (форматы паковки: none, LZMA, GZIP), распаковка\запаковка полных прошивок для RockChip (RKFW\RKAF)
Подробнее про утилиту, список протестированных устройств , инструкция, скрины и логи тут.

AndImgTool версия 1.3.0 Обновлено: 30.12.2014 релиз и подробности тут
— Добавлена поддержка распаковки\запаковки x86 загрузочных образов (функционал перенесен из утилиты xImgTool)

AndImgTool версия 1.2.2 AndImgTool_1_2_2.rar ( 196.73 КБ )
Обновлено: 22.10.2014 — обновление функционала, подробности тут
AndImgTool версия 1.2.1 Обновлено: 13.08.2014 — исправлены найденные ошибки
AndImgTool версия 1.2.0 AndImgTool_1_2_0.rar ( 196.16 КБ )
Обновлено: 10.07.2014
— добавлен функционал по поддержке кернела с XZ-компрессией
— добавлен функционал по распаковке рамдиска сжатого LZMA для формата Android Boot Image
— изменен алгоритм запаковки в LZMA (для большей схожести при перепаковке оригинальных данных)
подробнее про изменения в этой версии, логи работы утилиты
AndImgTool версия 1.1.2 Обновлено: 12.06.2014 Промежуточная версия 1.1.2 с реализованной обработкой блоков с UBOOT-оберткой для формата Android Boot Image и описание этой обертки для блоков рамдиска и кернела, примеры и логи распаковки подобных образов тут
AndImgTool версия 1.1.1 AndImgTool_1_1_1.rar ( 115.14 КБ )
Обновлено: 20.05.2014 подробнее про изменения в этой версии, логи работы утилиты
AndImgTool версия 1.1.0 AndImgTool_1_1_0.rar ( 115.38 КБ )
Обновлено: 16.05.2014 подробнее про изменения в этой версии, логи работы утилиты
AndImgTool версия 1.0.0 AndImgTool_1_0_0.rar ( 109.14 КБ )
Первая версия
24.04.2014 ОБНОВЛЕНО В связи с тестированием новые версии выкладываются в постах темы, пока текущая версия утилиты 1.0.8, тестируется пересборка zImage (актуально для загрузочных образов UBOOT-OMAP)

Пробуйте и отписывайтесь о результатах, если все удачно распаковалось и собралось в рабочий вариант напишите производителя и модель устройства (добавлю в список проверенных устройств), если утилита не справилась с образом, то ко всему вышеперечисленному в своем сообщении прикрепите этот проблемный образ (вряд ли они будут больше 20 мегабайт).

ImgExtractor

— основная утилита для распаковки образов файловых систем типа system, userdata, cache, secro (расширение может быть любое, например img или ext4).
Поддерживаются следующие форматы файловых систем: EXT2\EXT3\EXT4\YAFFS2\CRAMFS, форматы структуры образов (обертки) SPARSE\SIN( 1, 2 и 3 версии)\MOTO, поддерживается конвертация образа файловой системы формата EXT4 из обертки SIN или SPARSE непосредственно в EXT4, реализован вывод информации о суперблоке для образов файловых систем, дальше будет развиваться именно эта утилита.

ImgExtractor версия 1.3.7 Обновлено: 13.02.2015 релиз и подробности тут
— добавлена поддержка распаковки образов SPARSE-Marvell для MOTO
— исправлено падение утилиты при распаковке образов содержащих файлы с символами «?»
— добавлена идентификация формата UBIFS и обертки MOTO внутри SPARSE формата
— добавлена конвертация образов из EXT3\EXT4 в SPARSE с разбиением на файлы меньшего размера

Прикрепленное изображение

Прикрепленное изображение

— утилита для распаковки\запаковки загрузочных образов (IMG, BIN) и контейнеров (INB, SZB, QSB ) для устройств на базе x86 Android Platform (Lenovo K900, Ramos i9, Asus ZenFone 4,5,6, ZTE Geek)

xImgTool версия 1.3.32xImgTool_1_3_32.rar ( 40.86 КБ )
ОБНОВЛЕНО: 06.11.2014
— поддержка нового размера блока bootstub
— сохранение новых атрибутов в блоке размеров
— при распаковке контейнера QSB части, участвующие при объединении в один файл, сохраняются в отдельной папке в оригинальном виде (особенно касается образов system и userdata)

В связи с тем, что основной функционал кухни перешел в единую утилиту AndImgTool, не требующую для своей работы никаких дополнительных CYGWIN DLL, настоятельно рекомендую использовать для работы с загрузочными образами именно AndImgTool (для образов файловых систем есть единая утилита ImgExtractor), поскольку пересборок кухни больше не планируется.

Мой вариант кухни для распаковки целиковых прошивок под Rockchip, MTK и их содержимого. Изначально делал эту модификацию под себя — для удобства вытаскивания файлов system из разных прошивок, оригинальная версия тут.

"Re-size" the .img for smaller SD-card. How to SHRINK a bootable SD card image

I have a 16 GB SD card with a Linux based OS for a Raspberry Pi. Most of the space is empty.

I want to share the SD .img with other people but if I use the command

it will create a 16 GB image. Too big.

Question

How can I re-size a 16GB SD card image into a smaller 4GB?

I have tried with GParted: it creates a partition with 4GB with no problem, however the whole .img of the SD card continues to be 16 GB with 12 GB of unallocated space.

https://amdy.su/wp-admin/options-general.php?page=ad-inserter.php#tab-8

GParted table

I have read the question and answer Cloning multiple partitions in Ubuntu, but I still cannot re-size the 16GB SD card into a 4GB one.

More info

Any advice is appreciated!

Please note: as observed by Melebius in a comment, the right word to use is shrink:

You cannot resize an SD card as it is hardware with a given capacity that cannot be changed. You clearly want to shrink an SD card image.

Leos313's user avatar

5 Answers 5

This article gives a solution that solves my problem (*). It is quite similar to the other one, but it better explains how to calculate and which meaning have the numbers and the partitions.

The key information was the use of the command truncate . Following the full solution in order to not lose the answer.

A preliminary step consists in cloning the SD card in your PC:

use lsblk to see which devices are available and if their partitions are mounted

unmount all partitions of the device you want to copy on your pc. For example:

create a copy of the whole sd card with all the partitions unmounted

Shrinking images on Linux

Context of the problem:

Having a myimage.img bigger then the hardware support (if it is smaller there should be no problem; however, using the same strategy, you can better fit the image in the hardware support).

The secret is to use standard Linux tools and instruments: GParted, fdisk and truncate .

Requirements:

  • A Linux PC
  • The .img you want to shrink ( myimage.img in this example)

Creating loopback device:

GParted is an application typically used to manage partition tables and filesystems. In order to shrink the image, GParted is going to be used along the first part of the answer.

GParted operates on devices, not simple files like images. This is why we first need to create a device for the image. We do this using the loopback-functionality of Linux.

Let’s enable enable the loopback:

Let’s request a new (free) loopback device:

The command returns the path to a free loopback device:

Let’s create a device of the image:

The device /dev/loop0 represents myimage.img . We want to access the partitions that are on the image, so we need to ask the kernel to load those too:

This should give us the device /dev/loop0p1 , which represents the first partition in myimage.img . We do not need this device directly, but GParted requires it.

Resize partition using GParted:

Let’s load the new device using GParted:

When the GParted application opens, it should appear a window similar to the following:

screenshot

Now notice a few things:

  • There is one partition.
  • The partition allocates the entire disk/device/image.
  • The partition is filled partly.

We want to resize this partition so that is fits its content, but not more than that.

Select the partition and click Resize/Move. A window similar to the following will pop up:

screenshot of dialog

Drag the right bar to the left as much as possible.

Note that sometimes GParted will need a few MB extra to place some filesystem-related data. You can press the up-arrow at the New size-box a few times to do so. For example, I pressed it 10 times (=10MiB) for FAT32 to work. For NTFS you might not need to at all.

Finally press Resize/Move. You will return to the GParted window. This time it will look similar to the following:

unallocated space on right

Notice that there is a part of the disk unallocated. This part of the disk will not be used by the partition, so we can shave this part off of the image later. GParted is a tool for disks, so it doesn’t shrink images, only partitions, we have to do the shrinking of the image ourselves.

Press Apply in GParted. It will now move files and finally shrink the partition, so it can take a minute or two, but most of the time it finishes quickly. Afterwards close GParted.

Now we don’t need the loopback-device anymore, so unload it:

Shaving the image:

Now that we have all the important data at the beginning of the image it is time to shave off that unallocated part. We will first need to know where our partition ends and where the unallocated part begins. We do this using fdisk :

Here we will see an output similar to the following:

Note two things in the output:

  • The partition ends on block 9181183 (shown under End )
  • The block-size is 512 bytes (shown as sectors of 1 * 512 )

We will use these numbers in the rest of the example. The block-size (512) is often the same, but the ending block (9181183) will differ for you. The numbers mean that the partition ends on byte 9181183512 of the file. After that byte comes the unallocated-part. Only the first 9181183512 bytes will be useful for our image.

Next we shrink the image-file to a size that can just contain the partition. For this we will use the truncate command (thanks uggla!). With the truncate command need to supply the size of the file in bytes. The last block was 9181183 and block-numbers start at 0. That means we need (9181183+1)*512 bytes. This is important, else the partition will not fit the image. So now we use truncate with the calculations:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *