symba (779893), страница 34

Файл №779893 symba (Symbian Books) 34 страницаsymba (779893) страница 342018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 34)

It is a value specific to the plug-in but, in most cases, it is equalto the binary logarithm of the divisor of the ratio of the image to thedestination size.TInt ReducedSize(const TSize& aOriginalSize,TInt aReductionFactor,TSize& aReducedSize) const• aOriginalSize is the frame’s original size which can be obtainedfrom TFrameInfo.• aReductionFactor is the scaling coefficient obtained by callingthe ReductionFactor method.• aReducedSize is an output value which repesents a size for thegiven scaling coefficient.The return value is a standard error code, where KErrNone representssuccessful operation (as usual) and also means that aReducedSize hasbeen set to a valid value.This two-step process is required due to the simple fact that differentdecoder plug-ins may apply different logic as to what scaling coefficientsmean, the coefficient range availability and number rounding (whichusually depends on the underlying image format).To illustrate this, try deciding the output image size in a case when anend user asks for an image of size (35,33) to be decoded to size (15,16).Converting the FrameNow we have sorted out the destination size (well, the destination sizeadjusted to the closest possible match which the decoder plug-in canmanage), it is time to convert the frame into a bitmap.

This operationdoes not require any additional effort in comparison to what was done inSection 6.2.1. The only difference is that the calculated destination imagesize is used when creating the, output bitmap instead of the originalimage size:156IMAGE CONVERSION LIBRARYconst TSize frameSize( frameInfo.iFrameCoordsInPixels.Size() );// calculate the reduction factor for the given desired sizeTInt reductionFactor = iDecoder->ReductionFactor(frameSize,aDesiredSize);// try to get the size object for the given reduction factorUser::LeaveIfError( iDecoder->ReducedSize(frameSize, reductionFactor,aEffectiveSize) );// now create a bitmapUser::LeaveIfError( iBitmap->Create(aEffectiveSize,frameInfo.iFrameDisplayMode) );The image decoder plug-in tries to decode the frame so it fits into thedestination bitmap as well as possible.So why can’t we simply create a bitmap of the desired destination sizeand assume that the decoder will adjust it automatically? The answer issimple – a decoder plug-in (at least those which are supplied by Symbian)never adjusts the destination bitmap size because it would destroy thecontents; rather, it renders the image into the top-left corner of the bitmap.When the destination size can’t be matched exactly, either the outputcontains a border or an error code is returned and no image decodingtakes place.

The latter may happen when the destination size cannot becreated due to restrictions on the scaling coefficient range or if the givenplug-in doesn’t support downscaling.Implementing the ConversionNow let us translate the algorithm from Figure 6.4 into a piece of code.For the time being we are not going to use bitmap scaling to reach thedesired destination image size.The user of CalculateEffectiveSize() has to decide if the effective size satisfies their needs.

In the case where the smallest achievablesize is too big, you should use bitmap scaling to further reduce the scaleof the output bitmap.// Calculate the best possible match for the desired destination size// Will return error if no downscaling is supported by the plug-inTInt CSimpleDecodeHandler::CalculateEffectiveSize(const TSize& aDesiredSize,TInt aFrameNo, TSize& aEffectiveSize) const{const TFrameInfo& frameInfo = iDecoder->FrameInfo(aFrameNo);// where the frame is fully scalable, we do not need to use the// reduction factor as the decoder scales to any destination sizeif ((frameInfo.iFlags & TFrameInfo::EFullyScaleable) ==TFrameInfo::EFullyScaleable)DECODING IMAGES157{// if the aspect ratio has to be preserved, then we should calculate// the effective size taking into account the original size.// This is left as an exercise for the reader.aEffectiveSize = aDesiredSize;return KErrNone;}// get the original frame sizeconst TSize frameSize( frameInfo.iFrameCoordsInPixels.Size() );TInt error;// calculate the reduction factor for the given desired sizeTInt reductionFactor = iDecoder->ReductionFactor(frameSize,aDesiredSize);do{// try to get the size object for the given reduction factorerror = iDecoder->ReducedSize(frameSize, reductionFactor,aEffectiveSize);// An error usually means that the downscaling coefficient required is// too big so we try reducing it until we get a size which is// supported} while (error != KErrNone && --reductionFactor > 0);// Downscaling is not available, as reduction factor of 0 means the// original sizeif (reductionFactor < 0){return KErrNotSupported;}return error;}6.2.5 Decoding ThumbnailsThe CImageDecoder class also has support for decoding image thumbnails.

This support is fairly generic and even decoders for image formatsthat don’t have a thumbnail concept may implement it by generatingthumbnails from a normal image on request.However simple the API is, this feature is a bit tricky to use. CImageDecoder::SetImageTypeL() can be used to switch between imagetypes. You should use EImageTypeThumbnail for the thumbnail andEImageTypeMain for the main image. It is possible to call this methodmany times thus switching back and forth between thumbnail and mainimage.// By default, the image decoder uses the main image, so there is no// need to call iDecoder->SetImageTypeL(CImageDecoder::EImageTypeMain);const TFrameInfo mainImageInfo( iDecoder->FrameInfo(aFrameNo) );158IMAGE CONVERSION LIBRARY// try to switch to the thumbnail image of the given frameTRAPD(error, iDecoder->SetImageTypeL(CImageDecoder::EImageTypeThumbnail));TFrameInfo thumbnailInfo;// read the thumbnail information if there is oneif (error == KErrNone){ // using the first frame in this examplethumbnailInfo = iDecoder->FrameInfo(0);}If SetImageTypeL(EImageTypeThumbnail) succeeds, the decoder object switches to the thumbnail data so the thumbnail ‘frame’information is seen instead of the main image frame information.If SetImageTypeL(EImageTypeMain) is called, the image frameinformation is swapped back.We are not taking a reference to TFrameInfo, as was done previously,but a full copy of the class.

This is needed in order to protect ourselvesfrom the FrameInfo() implementation details as otherwise there isa risk of data mutability caused by the SetImageTypeL() call.6.2.6 Decoder Creation OptionsWe have explored the basic (and the most common) use cases for imagedecoding, so now is the time to dive into some optional parameters whichcan be specified during the creation of the image decoder object. Theseparameters can not be changed once the object has been created.

Theseoptions are defined in the CImageDecoder::TOptions enumerationin Table 6.3.It is possible to request several options at a time by combiningthem using the bitwise or operator. The result must be of CImageDecoder::TOptions type so it can be type-cast or you can construct anew object as follows:iDecoder = CImageDecoder::FileNewL(iFs, aFileName,CImageDecoder::TOptions(CImageDecoder::EAllowGeneratedMask |CImageDecoder::EOptionAlwaysThread));6.2.7 DRM Content SupportThe CImageDecoder API has full support for handling DRM content.There are several CImageDecoder::FileNewL() overloads whichcan be used to create a decoder for decoding a DRM-protected image.DECODING IMAGES159Table 6.3 The CImageDecoder::TOptions EnumerationEOptionNoneThis option means ‘nothing special has beenrequested’; it is used by default if no other optionshave been specified.EOptionNoDitherThis option instructs the decoder object not to applycolor dithering when a frame is being decoded to acolor mode other than native one i.e.

the one whichcan be retrieved using the iFrameDisplayModemember of the frame information structure.Note: Color dithering is a rather expensive operation,so if you care more about performance than quality,then it is better to specify this flag.EOptionAlwaysThreadThis option allows an API user to ask the frameworkto create a decoder object in a separate operatingsystem thread. This is often useful when the responsiveness of the application user interface is a toppriority during the decoding operation. Creating anOS thread involves some overhead, in that it takeslonger to create the decoder, consumes slightly morememory and involves inter-thread communication asthe framework will have to marshal a vast majority ofAPI calls into another thread.Note: Use of this option still requires the applicationto respect the active scheduler.

An application mustnever call User::WaitForRequest() to wait forcompletion of the CImageDecoder::Convert()call, as the framework itself may use activeobjects during the decoding process to communicatebetween threads and this would cause a deadlockeven if the decoder object operates in a separatethread.EOptionAllowZeroFrameOpenThis flag instructs the framework to successfully complete decoder object creation even if there is notenough data to create even one frame informationstructure. This flag is used during streamed datadecoding.Note: If this flag has been specified, then anapplication checks IsImageHeaderProcessingComplete() when decoder creation fails, in orderto determine if the frame information has been fullypopulated.(continued overleaf )160IMAGE CONVERSION LIBRARYTable 6.3 (continued )EAllowGeneratedMaskThis option instructs the decoder to automaticallygenerate a mask bitmap when no transparency information is present in the image.

Характеристики

Тип файла
PDF-файл
Размер
1,13 Mb
Материал
Тип материала
Высшее учебное заведение

Список файлов книги

Свежие статьи
Популярно сейчас
Зачем заказывать выполнение своего задания, если оно уже было выполнено много много раз? Его можно просто купить или даже скачать бесплатно на СтудИзбе. Найдите нужный учебный материал у нас!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6476
Авторов
на СтудИзбе
304
Средний доход
с одного платного файла
Обучение Подробнее